开发者

Reading incoming HTTP headers with node.js

Now as example, I'm getting an response which has partially the key/values as an javascript object:

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

I can easily read out and log the status message by: headers.status but when I try to log the content-encoding (which I need in this particular situation) it errors on:

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

How am I suppose to get/read/log it's content-encoding value?开发者_如何学Go

Greets,

m0rph3v5


Javascript also supports square bracket notation for referring to properties so if headers is an appropriate object, you can use headers['content-encoding'].


JavaScript properties have names as you know. When the name is a legal identifier and you know the literal name you want when you're writing the code, you can use it with dotted notation.

var foo = headers.foo;

When the name isn't a legal identifier, or if you want to determine the name you're looking up at runtime, you can use a string:

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

or

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

or even

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

As you can see, it doesn't have to be a literal string. This is very handy for general-purpose functions that have to accept a property name as a function argument or similar.

Note that property names are case sensitive.


I think you should install the very good express framework. I really simplifies node.js webdevelopment.

You could install it using npm

npm install express

This snippet shows you how to set headers and read headers

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 from command line

$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

The log outputting the header send via curl to node server:

$ node mo.js 
3434
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜