如何在 Node.js 上的 Express.js 中获取 GET(查询字符串)变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6912584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get GET (query string) variables in Express.js on Node.js?
提问by XMen
Can we get the variables in the query string in Node.js just like we get them in $_GETin PHP?
我们可以在 Node.js 中获取查询字符串中的变量,就像我们$_GET在 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?
我知道在 Node.js 中我们可以获取请求中的 URL。有没有获取查询字符串参数的方法?
采纳答案by Marcus Granstr?m
In Express it's already done for you and you can simply use req.queryfor that:
在 Express 中,它已经为您完成,您可以简单地使用req.query:
var id = req.query.id; // $_GET["id"]
Otherwise, in NodeJS, you can access req.urland the builtin urlmodule to [url.parse]
(https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost) it manually:
否则,在NodeJS 中,您可以手动访问req.url和内置url模块到 [url.parse] ( https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost) 它:
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
回答by whitequark
Since you've mentioned Express.js in your tags, here is an Express-specific answer: use req.query. E.g.
由于您在标签中提到了 Express.js,这里是一个特定于 Express 的答案:使用 req.query。例如
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});
app.listen(3000);
回答by mikermcneil
In Express, use req.query.
在 Express 中,使用req.query.
req.paramsonly gets the route parameters, not the query string parameters. See the expressor sailsdocumentation:
req.params只获取路由参数,不获取查询字符串参数。请参阅快递或帆文档:
(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.
(req.params) 检查路由参数,例如:/user/:id
(req.query) 检查查询字符串参数,例如:?id=12 检查 urlencoded body 参数
(req.body), ex: id=12 要使用 urlencoded 请求体,req.body 应该是一个对象。这可以通过使用 _express.bodyParser 中间件来完成。
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').
也就是说,大多数情况下,您希望获得参数的值而不管其来源。在这种情况下,请使用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)
旁注 - 如果您的目标是获得所有三种类型的请求参数的交集(类似于 PHP 的$_REQUEST),您只需要将参数合并在一起 - 这是我在 Sails 中设置的方法。请记住,路径/路由参数对象 ( req.params) 具有数组属性,因此顺序很重要(尽管这可能会在 Express 4 中发生变化)
回答by Cris-O
For Express.js you want to do req.params:
对于 Express.js 你想做req.params:
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
回答by Grant Li
I learned from the other answers and decided to use this code throughout my site:
我从其他答案中了解到,并决定在我的整个网站中使用此代码:
var query = require('url').parse(req.url,true).query;
Then you can just call
然后你可以打电话
var id = query.id;
var option = query.option;
where the URL for get should be
get 的 URL 应该在哪里
/path/filename?id=123&option=456
回答by bigboss
//get query¶ms in express
//etc. example.com/user/000000?sex=female
app.get('/user/:id', function(req, res) {
const query = req.query;// query = {sex:"female"}
const params = req.params; //params = {id:"000000"}
})
回答by Steven Spungin
If you are using ES6and Express, try this destructuringapproach:
如果您使用ES6和Express,请尝试以下destructuring方法:
const {id, since, fields, anotherField} = request.query;
In context:
在上下文中:
const express = require('express');
const app = express();
app.get('/', function(req, res){
const {id, since, fields, anotherField} = req.query;
});
app.listen(3000);
You can use default values with destructuringtoo:
您也可以使用默认值destructuring:
// sample request for testing
const req = {
query: {
id: '123',
fields: ['a', 'b', 'c']
}
}
const {
id,
since = new Date().toString(),
fields = ['x'],
anotherField = 'default'
} = req.query;
console.log(id, since, fields, anotherField)
回答by Omkar Bandkar
There are 2 ways to pass parameters via GET method
Method 1 :
The MVC approach where you pass the parameters like /routename/:paramname
In this case you can use req.params.paramname to get the parameter value For Example refer below code where I am expecting Id as a param
link could be like : http://myhost.com/items/23
有两种通过 GET 方法传递参数的方法
方法 1:MVC 方法,您传递参数,例如 /routename/:paramname
在这种情况下,您可以使用 req.params.paramname 来获取参数值例如,请参阅下面的代码,其中我我期待 Id 作为参数
链接可能是这样的:http: //myhost.com/items/23
var express = require('express');
var app = express();
app.get("items/:id", function(req, res) {
var id = req.params.id;
//further operations to perform
});
app.listen(3000);
Method 2 :
General Approach : Passing variables as query string using '?' operator
For Example refer below code where I am expecting Id as a query parameter
link could be like : http://myhost.com/items?id=23
方法 2:一般方法:使用 '?' 将变量作为查询字符串传递 操作符
例如参考下面的代码,我期望 Id 作为查询参数
链接可能是这样的:http: //myhost.com/items?id=23
var express = require('express');
var app = express();
app.get("/items", function(req, res) {
var id = req.query.id;
//further operations to perform
});
app.listen(3000);
回答by RobertPitt
You should be able to do something like this:
你应该能够做这样的事情:
var http = require('http');
var url = require('url');
http.createServer(function(req,res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query); //{Object}
res.end("End")
})
回答by Mars Robertson
UPDATE 4 May 2014
2014 年 5 月 4 日更新
Old answer preserved here: https://gist.github.com/stefek99/b10ed037d2a4a323d638
旧答案保留在这里:https: //gist.github.com/stefek99/b10ed037d2a4a323d638
1) Install express: npm install express
1)安装快递: npm install express
app.js
应用程序.js
var express = require('express');
var app = express();
app.get('/endpoint', function(request, response) {
var id = request.query.id;
response.end("I have received the ID: " + id);
});
app.listen(3000);
console.log("node express app started at http://localhost:3000");
2) Run the app: node app.js
2)运行应用程序: node app.js
3) Visit in the browser: http://localhost:3000/endpoint?id=something
3)在浏览器中访问: http://localhost:3000/endpoint?id=something
I have received the ID: something
我收到了身:东西
(many things have changed since my answer and I believe it is worth keeping things up to date)
(自从我的回答以来,很多事情都发生了变化,我相信值得保持最新状态)

