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

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. Is there a method to get the query string parameters?


Yes you can access req.url and the builtin url module to url.parse it manually:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

However, in expressjs it's already done for you and you can simply use req.query for that:

var id = req.query.id; // $_GET["id"]

Since you've mentioned Express.js in your tags, here is an Express-specific answer: use req.query. Eg

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);
});

app.listen(3000);

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)

链接地址: http://www.djcxy.com/p/22758.html

上一篇: XNA游戏无法部署到WP7模拟器

下一篇: 如何在Node.js的Express.js中获取GET(查询字符串)变量?