I know how to get the params for queries like this:
app.get('/sample/:id',routes.sample);
In this case, I can use req.params.id to get the parameter (e.g. 2 in /sample/2).
However, for url like /sample/2?color=red, how can I access the variabe color?
I tried req.params.color but it didn't work.
Does anyone have ideas about this? Thanks!
So, after checking out the express reference, I found that req.query.color would return me the value I'm looking for.
Update: req.param() is now deprecated, so going forward do not use this answer.
Your answer is the preferred way to do it, however I thought I'd point out that you can also access url, post, and route parameters all with req.param(parameterName, defaultValue).
In your case:
var color = req.param('color');
From the express guide:
lookup is performed in the following order:
- req.params
- req.body
- req.query
Note the guide does state the following:
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
However in practice I've actually found req.param() to be clear enough and makes certain types of refactoring easier.
@Zugwait's answer is correct. req.param() is deprecated. You should use req.params, req.query or req.body.
But just to make it clear:
req.params will be populated with only the route values. That is, if you have a route like /users/:id, you get access id in req.params.id or req.params['id'].
req.query and req.body will be populated with all params, regardless of whether or not they are in the route.
So, answering your questions, as color is not in the route, you should be able to get it using req.query.color or req.query['color'].