简体   繁体   English

如何使用Node获取网站的HTTP响应标头

[英]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. 我想要的是使用Node JS获得http响应标头以及给定网站的状态代码 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 用google尝试后,显示给我的响应代码是301,这显然是错误的

For that example, I believe the correct code would be "200" for OK. 对于该示例,我认为正确的代码应为“ 200”。 Plus this one doesnt show all the headers. 另外,这个不显示所有标题。

You can see that if I cURL google.com I get a 301, redirect 您可以看到,如果我对google.com 进行了网址访问,则会收到301,重定向 在此处输入图片说明

This is because google.com is redirecting me to www.google.com . 这是因为google.com将我重定向到www.google.com However, if I cURL www.google.com , it gives me this response, 但是,如果我cURL www.google.com ,它会给我这个响应,

在此处输入图片说明

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 至于标题,根据https模块文档 (显示以下示例),它们应位于res.headers

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); 如您所见,它们使用console.log('headers:', res.headers);打印标题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 您可以使用res.headers['INSERT-HEADER-NAME-HERE']访问给定的标头,其中INSERT-HEADER-NAME-HERE被替换为您要使用的标头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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