请求节点模块未提供 html

request node module not giving html

我正在使用请求 nodejs 模块为以下网站获取 html:

var request = require('request');

request("http://www.thenewschool.org/", function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log("body>>>>>>>>>>");
    } else {
        console.log("error>>>>>>>>>"+error);
        console.log("response statusCode>>>>>>>>>"+response.statusCode);
        console.log("response body>>>>>>>>>"+response.body);
    }
})

这给了我这个输出

error>>>>>>>>>null

response statusCode>>>>>>>>>403

response body>>>>>>>>>Sorry, this request has been blocked due to an invalid user agent.

这在大多数情况下都是通过的,但在这种情况下失败了,谁能帮我解决这个问题。

您收到了 HTTP 403 错误代码:访问被禁止。

这可能意味着您的请求已 "profiled" 为 "we don't want you here" :

  • 这可能是因为您的 IP 已被标记
  • 或者因为您缺少 header 会使您的请求看起来像真实浏览器的请求。最有可能的是 user-agent header 给定 body 的答案

您只需在 headers 中传递 user-agent(因为 URL 需要它),例如:

var options = {
  headers: {'user-agent': 'node.js'}
}

request("http://www.thenewschool.org/", options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log("body>>>>>>>>>>" + body);
  } else {
    console.log("error>>>>>>>>>"+error);
    console.log("response statusCode>>>>>>>>>"+response.statusCode);
    console.log("response body>>>>>>>>>"+response.body);
  }
})