用node.js读取传入的HTTP头

现在作为例子,我得到一个部分的关键/值作为一个JavaScript对象的响应:

status: '200 OK', 'content-encoding': 'gzip' 

我可以很容易地读出和logging状态消息:headers.status,但是当我尝试logging内容编码(我需要在这种特殊情况下)它的错误:

 headers.'content-encoding' <- obviously the quotes it doesn't like headers.content-encoding <- obviously the '-' it doesn't like 

我想如何获取/读取/logging它的内容编码值?

映入眼帘,

m0rph3v5

JavaScript还支持用于引用属性的方括号表示法,所以如果headers是适当的对象,则可以使用headers['content-encoding']

如您所知,JavaScript属性具有名称。 当这个名字是一个合法的标识符,并且当你写代码的时候你知道你想要的文字名字的时候,你可以用虚线的符号来使用它。

 var foo = headers.foo; 

当名称不是合法的标识符,或者如果你想确定你在运行时查找的名字,你可以使用一个string:

 var encoding = headers['content-encoding']; 

要么

 var name = 'content-encoding'; var encoding = headers[name]; 

甚至

 var x = 'encoding'; var encoding = headers['content-' + x]; 

正如你所看到的,它不一定是一个文字string。 对于必须接受属性名称作为函数参数或类似函数的通用函数,这非常方便。

请注意,属性名称区分大小写。

我认为你应该安装非常好的expression框架。 我真的简化了node.js web开发。

你可以使用npm来安装它

 npm install express 

这段代码展示了如何设置标题和读取标题

 var express = require('express'); var app = express.createServer(); app.get('/', function(req, res){ console.log(req.header('a')); res.header('time', 12345); res.send('Hello World'); }); app.listen(3000); 

从命令行curl

 $curl http://localhost:3000/ -H "a:3434" -v * About to connect() to localhost port 3000 (#0) * Trying ::1... Connection refused * Trying 127.0.0.1... connected * Connected to localhost (127.0.0.1) port 3000 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.21.2 (i686-pc-linux-gnu) libcurl/7.21.2 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18 > Host: localhost:3000 > Accept: */* > a:3434 > < HTTP/1.1 200 OK < X-Powered-By: Express < time: 12345 < Content-Type: text/html; charset=utf-8 < Content-Length: 11 < Date: Tue, 28 Dec 2010 13:58:41 GMT < X-Response-Time: 1ms < Connection: keep-alive < * Connection #0 to host localhost left intact * Closing connection #0 Hello World 

输出头的日志通过curl发送到节点服务器:

 $ node mo.js 3434