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

前端 未结 26 3498
庸人自扰
庸人自扰 2020-11-21 23:53

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.

26条回答
  •  醉话见心
    2020-11-22 00:02

    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)

提交回复
热议问题