How to get a URL parameter in Express?
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
You can do something like req.param('tagId')
If you want to grab the query parameter value in the URL, follow below code pieces
//url.localhost:8888/p?tagid=1234req.query.tagidORreq.param.tagid
If you want to grab the URL parameter using Express param function
Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.
This can be used for validations or grabbing important information about item.
An example for this would be:
// parameter middleware that will run before the next routesapp.param('tagid', function(req, res, next, tagid) {// check if the tagid exists// do some validations// add something to the tagidvar modified = tagid+ '123';// save name to the requestreq.tagid= modified;next();});// http://localhost:8080/api/tags/98app.get('/api/tags/:tagid', function(req, res) {// the tagid was found and is available in req.tagidres.send('New tag id ' + req.tagid+ '!');});