【问题标题】:How to get a website's HTTP response headers with Node如何使用 Node 获取网站的 HTTP 响应标头
【发布时间】:2019-07-10 19:30:09
【问题描述】:

我整天都在寻找这个。我想要的只是使用 Node JS 获取给定网站的 http 响应标头 以及 状态代码。就这么简单。

对于这个简单的问题,我检查的所有答案和文档似乎都过于复杂,而且我似乎无法让它们发挥作用。

例如,一个答案为我提供了此代码

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

用google试了一下,它显示的响应码是301,这显然是错误的

对于那个例子,我相信正确的代码应该是“200”表示 OK。加上这个没有显示所有的标题。

【问题讨论】:

  • 301 是正确的状态码,表示页面已被重定向。您正在尝试点击google.com,然后重定向到https://google.com,从而重定向
  • 你应该先阅读HTTP Redirections。此外,验证here 地址google.com 返回的状态码是301,然后是302,最后是200。这就是Google 将用户重定向到他们的HTTPS 协议的方式。默认情况下,调用 google.com 是 HTTP 协议。尝试直接调用:https://www.google.com 以防止重定向。
  • 使用该代码直接在 https 上调用 google 会出现错误
  • @RaviMattar 直接致电https://www.google.com
  • 我怎样才能得到所有的状态码?

标签: javascript node.js http-headers


【解决方案1】:

如果我 cURL google.com I get a 301, redirect 你可以看到

这是因为google.com 将我重定向到www.google.com。但是,如果我 cURL www.google.com,它会给我这个响应,

这是网页。至于标题,它们应该在res.headers 根据https module documentation 显示以下示例

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);
});

如您所见,他们使用console.log('headers:', res.headers); 打印标题。您可以使用 res.headers['INSERT-HEADER-NAME-HERE'] 访问给定的标头,其中 INSERT-HEADER-NAME-HERE 替换为 the header that you want to use

【讨论】:

  • 各位大神,非常感谢!我终于明白了一点,并设法让它发挥作用。
猜你喜欢
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2017-11-06
相关资源
最近更新 更多