Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a URL parameter in Express?

I am facing an issue on getting the value of tagid from my URL: localhost:8888/p?tagid=1234.

Help me out to correct my controller code. I am not able to get the tagid value.

My code is as follows:

app.js:

var express = require('express'),   http = require('http'),   path = require('path'); var app = express(); var controller = require('./controller')({   app: app });  // all environments app.configure(function() {   app.set('port', process.env.PORT || 8888);   app.use(express.json());   app.use(express.urlencoded());   app.use(express.methodOverride());   app.use(app.router);   app.use(express.static(path.join(__dirname, 'public')));   app.set('view engine', 'jade');   app.set('views', __dirname + '/views');   app.use(app.router);   app.get('/', function(req, res) {     res.render('index');   }); }); http.createServer(app).listen(app.get('port'), function() {   console.log('Express server listening on port ' + app.get('port')); }); 

Controller/index.js:

function controller(params) {   var app = params.app;   //var query_string = request.query.query_string;    app.get('/p?tagId=/', function(request, response) {     // userId is a parameter in the url request     response.writeHead(200); // return 200 HTTP OK status     response.end('You are looking for tagId' + request.route.query.tagId);   }); }  module.exports = controller; 

routes/index.js:

require('./controllers'); /*  * GET home page.  */  exports.index = function(req, res) {   res.render('index', {     title: 'Express'   }); }; 
like image 907
user2834795 Avatar asked Nov 20 '13 07:11

user2834795


People also ask

How do I find the parameter of a URL?

For getting the URL parameters, there are 2 ways: By using the URLSearchParams Object. By using Separating and accessing each parameter pair.

How get full URL in Express?

To get the full URL in Express and Node. js, we can use the url package. to define the fullUrl function that takes the Express request req object. And then we call url.


2 Answers

Express 4.x

To get a URL parameter's value, use req.params

app.get('/p/:tagId', function(req, res) {   res.send("tagId is set to " + req.params.tagId); });  // GET /p/5 // tagId is set to 5 

If you want to get a query parameter ?tagId=5, then use req.query

app.get('/p', function(req, res) {   res.send("tagId is set to " + req.query.tagId); });  // GET /p?tagId=5 // tagId is set to 5 

Express 3.x

URL parameter

app.get('/p/:tagId', function(req, res) {   res.send("tagId is set to " + req.param("tagId")); });  // GET /p/5 // tagId is set to 5 

Query parameter

app.get('/p', function(req, res) {   res.send("tagId is set to " + req.query("tagId")); });  // GET /p?tagId=5 // tagId is set to 5 
like image 137
maček Avatar answered Oct 10 '22 23:10

maček


You can do something like req.param('tagId')

like image 44
tomahim Avatar answered Oct 11 '22 00:10

tomahim