Javascript 如何使用 Express 解析查询字符串中的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14669669/
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 parse variables in querystring using Express?
提问by user1031947
I have a request being sent to the server:
我有一个请求被发送到服务器:
"/stuff?a=a&b=b&c=c"
Using express, how do I get these values?
使用 express,我如何获得这些值?
I have tried the following...
我尝试了以下...
app.get( "/stuff?:a&:b&:c", function( req, res ){});
...however it does not seem to recognize the route.
...但是它似乎无法识别路线。
Thanks (in advance) for your help.
在此先感谢您的帮助。
回答by Dmitry Manannikov
It's not a good idea to use a query string inside a route.
在路由中使用查询字符串不是一个好主意。
In Express logic you need create a route for "/stuff". The query string will be available in req.query.
在 Express 逻辑中,您需要为“/stuff”创建一个路由。查询字符串将在req.query.
回答by Marco
You can declare your route directly with /stuff, then query parameters are accessible through req.query, which is a JSON object.
Here's your example:
您可以直接使用 声明您的路由/stuff,然后可以通过req.queryJSON 对象访问查询参数。这是你的例子:
app.get("/stuff", function(req, res) {
var a = req.query.a;
...
});
In your case, req.queryis equal to:
在您的情况下,req.query等于:
{ a: 'a',
b: 'b',
c: 'c' }
In Express' documentation (either 4.x and 3.x) you can find additional examples: Express - req.query.
在 Express 的文档(4.x 和 3.x)中,您可以找到其他示例: Express - req.query。

