305
votes

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).

5

5 Answers

372
votes

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

241
votes

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"
}
147
votes

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

67
votes
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']; 
1
votes
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"}