使用Express获取Node.js中的URL内容

And*_*w M 12 node.js express

使用Express框架时,如何在Node中下载URL的内容?基本上,我需要完成Facebook身份验证流程,但如果不获取OAuth令牌URL,我就无法做到这一点.

通常,在PHP中,我使用Curl,但Node是等价的?

cho*_*ovy 26

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});
Run Code Online (Sandbox Code Playgroud)

http://nodejs.org/docs/v0.4.11/api/http.html#http.get

  • 嗯??问题要求 HTML,而不是状态代码。 (3认同)
  • 感谢纯节点解决方案。虽然整个事件驱动的东西很酷,但请求模块的简单性使我正在处理的项目的代码更简单。因为我没有指定模块或无模块,我将把它标记为答案。 (2认同)
  • 我在http://stackoverflow.com/questions/6695143/how-to-make-web-service-calls-in-expressjs上找到了接受的答案,以便成为同一解决方案的更好示例. (2认同)

Abd*_*UMI 11

您将面临的问题是:某些网页使用JavaScript加载其内容.因此,您需要一个包,如After-Load模拟浏览器的行为,然后为您提供该URL的HTML内容.

var afterLoad = require('after-load');
afterLoad('https://google.com', function(html){
   console.log(html);
});
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,链接已损坏。这里是 npm 页面:https://www.npmjs.com/package/after-load (2认同)

Nat*_*hat 5

对于一个简单的 html 页面,使用 http 方式需要更多的代码行。

这是一个有效的方法:使用请求

var request = require("request");

request({uri: "http://www.sitepoint.com"}, 
    function(error, response, body) {
    console.log(body);
  });
});
Run Code Online (Sandbox Code Playgroud)

这是请求的文档:https : //github.com/request/request



使用 fetch 和 promise 的第二种方法:

    fetch('https://sitepoint.com')
    .then(resp=> resp.text()).then(body => console.log(body)) ; 
Run Code Online (Sandbox Code Playgroud)