Node.js: Difference between req.query[] and req.params
Given this route
app.get('/hi/:param1', function(req,res){} );
// regex version
app.get(/^\/hi\/(.*)$/, function(req,res){} );
// unnamed wild card
app.get('/hi/*', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
When you use a regular expression for the route definition, capture groups are provided in the array using
req.params[n]
, where n is the nth capture group. This rule is applied to unnamed wild card matches with string routes
Express req.params >>
Suppose you have defined your route name like this:
https://localhost:3000/user/:userId
which will become:
https://localhost:3000/user/5896544
Here, if you will print: request.params
{
userId : 5896544
}
so
request.params.userId = 5896544
so request.params is an object containing properties to the named route
and request.query comes from query parameters in the URL eg:
https://localhost:3000/user?userId=5896544
request.query
{
userId: 5896544
}
so
request.query.userId = 5896544
req.params
contains route parameters (in the path portion of the URL), and req.query
contains the URL query parameters (after the ?
in the URL).
You can also use req.param(name)
to look up a parameter in both places (as well as req.body
), but this method is now deprecated.