Ravi Mattar
Ravi Mattar

Reputation: 185

How to get a website's HTTP response headers with Node

I've been searching the entire day for this. All I want is to get the http response headers plus the status code for a given website using Node JS. That simple.

All the answers and documentation I checked seem far too hideously too complicated for this simple problem, plus I don't seem to be able to get them to work.

For example, one answer provided me with this code

const https = require('https')
const options = {
  hostname: 'google.com'
}

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', (d) => {
    process.stdout.write(d)
  })
})

req.on('error', (error) => {
  console.error(error)
})

req.end()

After trying it with google, the response code it shows me is 301, which is obvisouly just wrong

For that example, I believe the correct code would be "200" for OK. Plus this one doesnt show all the headers.

Upvotes: 0

Views: 910

Answers (1)

Ben
Ben

Reputation: 244

You can see that if I cURL google.com I get a 301, redirect enter image description here

This is because google.com is redirecting me to www.google.com. However, if I cURL www.google.com, it gives me this response,

enter image description here

which is the webpage. As far as the headers, they should be in res.headers according to the https module documentation which shows the following example

const https = require('https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});

As you can see, they print the headers using console.log('headers:', res.headers);. You can access a given header by using res.headers['INSERT-HEADER-NAME-HERE'] where INSERT-HEADER-NAME-HERE is replaced with the header that you want to use

Upvotes: 1

Related Questions