Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 386
Hanfei Sun Avatar asked Jun 09 '13 08:06

Hanfei Sun


People also ask

Can we send parameters in GET request?

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.

How do I get the request body in Express?

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.


2 Answers

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 }) 
like image 114
Hanfei Sun Avatar answered Oct 08 '22 07:10

Hanfei Sun


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);  }); 
like image 30
satyam kumar Avatar answered Oct 08 '22 05:10

satyam kumar