如何使用 NodeJS 连接从请求中提取请求 http 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13147693/
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 extract request http headers from a request using NodeJS connect
提问by Alex Spurling
I'd like to get the "Host" header of a request made using Node JS's connect library bundle. My code looks like:
我想获取使用 Node JS 的连接库包发出的请求的“主机”标头。我的代码看起来像:
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
var host = req.???
})
.listen(3000);
The documentation for connect is here but I don't see anything detailing the API of the reqobject in the above code. http://www.senchalabs.org/connect/
connect 的文档在这里,但我req在上面的代码中没有看到任何详细说明对象API 的内容。http://www.senchalabs.org/connect/
Edit: Note a successful answer must point to the documentation (I need this to verify which version provided the API I'm looking for).
编辑:注意一个成功的答案必须指向文档(我需要这个来验证哪个版本提供了我正在寻找的 API)。
回答by Sami
If you use Express 4.x, you can use the req.get(headerName)method as described in Express 4.x API Reference
如果你使用 Express 4.x,你可以使用Express 4.x API Reference 中req.get(headerName)描述的方法
回答by user2775422
To see a list of HTTP request headers, you can use :
要查看 HTTP 请求标头列表,您可以使用:
console.log(JSON.stringify(req.headers));
to return a list in JSON format.
以 JSON 格式返回列表。
{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
回答by Anatoliy
Check output of console.log(req)or console.log(req.headers);
检查console.log(req)或的输出console.log(req.headers);
回答by Bonkles
var host = req.headers['host'];
The headers are stored in a JavaScript object, with the header strings as object keys.
标头存储在 JavaScript 对象中,标头字符串作为对象键。
Likewise, the user-agent header could be obtained with
同样,用户代理标头可以通过
var userAgent = req.headers['user-agent'];

