Javascript 使用node.js读取传入的HTTP头

Javascript 使用node.js读取传入的HTTP头,javascript,json,variables,http-headers,node.js,Javascript,Json,Variables,Http Headers,Node.js,现在作为示例,我得到一个响应,其中部分键/值作为javascript对象: status: '200 OK', 'content-encoding': 'gzip' 我可以通过:headers.status轻松读取并记录状态消息,但当我尝试记录内容编码(在这种特殊情况下需要)时,它会在以下位置出错: headers.'content-encoding' <- obviously the quotes it doesn't like headers.content-encoding <

现在作为示例,我得到一个响应,其中部分键/值作为javascript对象:

status: '200 OK',
'content-encoding': 'gzip'
我可以通过:headers.status轻松读取并记录状态消息,但当我尝试记录内容编码(在这种特殊情况下需要)时,它会在以下位置出错:

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

headers.'content-encoding'Javascript还支持方括号表示法来引用属性,因此如果
headers
是适当的对象,您可以使用
headers['content-encoding']
Javascript属性的名称。如果名称是合法标识符,并且在编写代码时知道所需的文字名称,则可以将其与虚线符号一起使用

var foo = headers.foo;
如果名称不是合法标识符,或者如果要确定运行时要查找的名称,可以使用字符串:

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

甚至

var x = 'encoding';
var encoding = headers['content-' + x];
如您所见,它不必是文本字符串。这对于必须接受属性名称作为函数参数或类似参数的通用函数非常方便


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

我认为您应该安装非常好的框架。我真的简化了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 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

非常感谢,愚蠢的是,我用这种方式尝试的只是标题。['content-encoding']没有想到我会意外地将两者结合起来。:)总有第一次:-)祝你好运。
$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
$ node mo.js 
3434