Can we get the variables in the query string in Node.js just like we get them in $_GET
in PHP?
I know that in Node.js we can get the URL in the request.
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)