javascript - 请求 Node 模块不提供 html

标签 javascript node.js request npm

我正在使用请求 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.

这在大多数情况下都是通过的,但在这种情况下失败了,有人可以帮我解决这个问题吗。

最佳答案

您只需在 header 中传递 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);
  }
})

关于javascript - 请求 Node 模块不提供 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30508971/

相关文章:

javascript - 如何从 Angular $http post 请求中获取 json 字符串

python - 从网站上的表格中获取数据

javascript - 无限滚动在 angularjs 的温泉列表中不起作用

javascript - VS2012 丢失的 JavaScript 调试器

javascript - 如果存在则追加到列表或在 dynamoDB 中添加列表

java - 松弛请求验证 : Can't compute matching request digest using signed secret

javascript - 如何在 Angularjs 中获取 $mdDialog 中的 HTML 元素

javascript - 当表单在数组中提交其获取JSON数据但显示错误时

javascript - 在 Hostinger 共享主机上安装 Node.js 的问题

node.js - 既然 connect 不再使用 parseCookie 方法,那么我们如何使用 express 获取 session 数据呢?