Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting HTTP headers with Node.js

Tags:

node.js

Is there a built in way to get the headers of a specific address via node.js?

something like,

var headers = getUrlHeaders("http://stackoverflow.com"); 

would return

HTTP/1.1 200 OK. Cache-Control: public, max-age=60. Content-Type: text/html; charset=utf-8. Content-Encoding: gzip. Expires: Sat, 07 May 2011 17:32:38 GMT. Last-Modified: Sat, 07 May 2011 17:31:38 GMT. Vary: *. Date: Sat, 07 May 2011 17:31:37 GMT. Content-Length: 32516. 
like image 973
lostsource Avatar asked May 07 '11 17:05

lostsource


People also ask

How do I view headers in node js?

To see a list of HTTP request headers, you can use : console. log(JSON. stringify(req.

What is HTTP header in node js?

The header tells the server details about the request such as what type of data the client, user, or request wants in the response. Type can be html , text , JSON , cookies or others.


2 Answers

This sample code should work:

var http = require('http'); var options = {method: 'HEAD', host: 'stackoverflow.com', port: 80, path: '/'}; var req = http.request(options, function(res) {     console.log(JSON.stringify(res.headers));   } ); req.end(); 
like image 134
clee Avatar answered Oct 05 '22 04:10

clee


Try to look at http.get and response headers.

var http = require("http");  var options = {   host: 'stackoverflow.com',   port: 80,   path: '/' };  http.get(options, function(res) {   console.log("Got response: " + res.statusCode);    for(var item in res.headers) {     console.log(item + ": " + res.headers[item]);   } }).on('error', function(e) {   console.log("Got error: " + e.message); }); 
like image 38
yojimbo87 Avatar answered Oct 05 '22 04:10

yojimbo87