425

I'd like to get the "Host" header of a request made using Node JS's connect library bundle. My code looks like:

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 req object in the above code. 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).

7 Answers 7

469

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

Sign up to request clarification or add additional context in comments.

3 Comments

Also aliased with the better-named req.header(headerName).
No need to bring in Express for basic functionality like this one. Instead use natively in NodeJS as mentioned below. nodejs.org/en/docs/guides/anatomy-of-an-http-transaction
...was it to difficult for them to call it getHeader()? javascript never fails to amaze. btw. .get()/header() are case insensitive but .headers[] is case-sensitive
367

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"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"
}

7 Comments

I found this more helpful than the accepted answer above. The JSON.stringify makes all the difference.
Totally- on a related note, you can also do: require('util').inspect(req.headers, {depth: null} if you want the equivalent of what you'd get in the Node REPL. Either way you end up w/ a string.
Why isn't req.headers included in the official Express documentation? expressjs.com/en/api.html#req
Stating the obvious here : headerValue = req.headers['headerName'];
They just document those properties that are not derived. There is a note in the Express documentation mentioned above: "The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods." that contains a link pointing to the Node documentation of the underlying object.
|
165

Check output of console.log(req) or console.log(req.headers);

9 Comments

How did you find out about req.headers? In which version is this field available?
@AlexSpurling nodejs.org/api/http.html#http_request_headers. Connect just extends types from Node's HTTP module -- http.ServerRequest and http.ServerResponse. Properties or events found in Node's documentation should also be available with Connect (and, by further extension, Express).
That makes more sense. Again, it would be good to know where to find that information (that the type of req is actually http.ServerRequest). The documentation doesn't appear to make this clear.
Type of req is http.IncomingMessage
This gist emulates http request and it may be useful for you: gist.github.com/3879071
|
94
var host = req.headers['host']; 

The headers are stored in a JavaScript object, with the header strings as object keys.

Likewise, the user-agent header could be obtained with

var userAgent = req.headers['user-agent']; 

4 Comments

NOTE: the named index value is FreakING!! case sensitative
As per @Steve comment about it being case sensitive all headers are lower-cased. So if you are setting the header "Origin" (capital 'O') then the only element in the request headers collection will be "origin" with a lowercase 'o'.
@Steve - FWIW, headers are not supposed to be case sensitive. The Http spec specifically says they are treated as case insensitive. For Http2 they must be lowercased for transmission, but that doesnt make them case sensitive on either end, so what we got is an http header implementation thats bugged =/.
that is because nodejs stores them like a dict. and those dict keys are case sensitive. Doesnt mean that i support that behavior, but that is the reason for it.
7
logger.info({headers:req.headers})

Output;

 "headers":{"authorization":"Basic bmluYWQ6bmluYWQ=","content-
type":"application/json","user-
agent":"PostmanRuntime/7.26.8","accept":"*/*","postman-token":"36e0d84a-
55be-4661-bb1e-1f04d9499574","host":"localhost:9012","accept-
encoding":"gzip, deflate, br","connection":"keep-alive","content-
length":"198"}

Comments

1

In express, we can use request.headers['header-name'], For example if you have set up a Bearer token in authorization header and want to retrieve the token, then you should write req.headers['authorization'], and you will get the string containing 'Bearer tokenString'.

Comments

0
  • To log all the headers from the request.
console.log(request?.headers);
{
    "x-correlation-id": "correlation-id-53d9fce3-ed09-4695-a51e-6febefb76bbb",
    "x-session-id": "session-id-6529e216-4af5-4b0d-96fd-db4f5f94ca4c",
    "x-user-id": "3"
}
  • For any specific header like host.
request.get('host');

OR

request?.headers['host'];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.