How to access the GET parameters after "?" in Express? How to access the GET parameters after "?" in Express? express express

How to access the GET parameters after "?" in Express?


So, after checking out the express reference, I found that req.query.color would return me the value I'm looking for.

req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'

Example:

GET /something?color1=red&color2=blue

Then in express, the handler:

app.get('/something', (req, res) => {    req.query.color1 === 'red'  // true    req.query.color2 === 'blue' // true})


Use req.query, for getting he value in query string parameter in the route.Refer req.query.Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){    console.log(req.query.name);    res.send('Response send to client::'+req.query.name);});


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.