node.js http 获取请求参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19029386/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:45:04  来源:igfitidea点击:

node.js http get request parameters

javascriptnode.jshttpexpress

提问by Alex Cebotari

I want to handle an HTTP request like this:

我想处理这样的 HTTP 请求:

GET http://1.2.3.4/status?userID=1234

But I can't extract the parameter userIDfrom it. I am using Express, but it's not helping me. For example, when I write something like the following, it doesn't work:

但我无法从中提取参数userID。我正在使用 Express,但它对我没有帮助。例如,当我编写如下内容时,它不起作用:

app.get('/status?userID=1234', function(req, res) {
  // ...
})

I would like to have possibility to take value 1234for any local parameter, for example, user=userID. How can I do this?

我希望有可能1234为任何本地参数取值,例如,user=userID. 我怎样才能做到这一点?

回答by hexacyanide

You just parse the request URL with the native module.

您只需使用本机模块解析请求 URL。

var url = require('url');
app.get('/status', function(req, res) {
  var parts = url.parse(req.url, true);
  var query = parts.query;
})

You will get something like this:

你会得到这样的东西:

query: { userID: '1234' }

Edit:Since you're using Express, query strings are automatically parsed.

编辑:由于您使用的是 Express,查询字符串会自动解析。

req.query.userID
// returns 1234