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 variable color
?
I tried req.params.color
but it didn't work.
get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.
Express has a built-in express. json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req . To access the parsed request body, use req.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With