Thursday 29 September 2016

How to get GET (query string) variables in Express.js on Node.js?

In Express, use req.query.


req.params only gets the route parameters, not the query string parameters. See the express or sails documentation:



(req.params) Checks route params, ex: /user/:id


(req.query) Checks query string params, ex: ?id=12 Checks urlencoded body params


(req.body), ex: id=12 To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.



That said, most of the time, you want to get the value of a parameter irrespective of its source. In that case, use req.param('foo').


The value of the parameter will be returned whether the variable was in the route parameters, query string, or the encoded request body.


Side note- if you're aiming to get the intersection of all three types of request parameters (similar to PHP's $_REQUEST), you just need to merge the parameters together-- here's how I set it up in Sails. Keep in mind that the path/route parameters object (req.params) has array properties, so order matters (although this may change in Express 4)

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...