简体   繁体   中英

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.

You can see that if I cURL google.com I get a 301, redirect 在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM