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

问题描述 投票:11回答:3

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

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

node.js express
3个回答
25
投票
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);
});

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


9
投票

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

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

2
投票

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

这是一种有效的方式:使用请求

var request = require("request");

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

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


2nd Method using fetch with promises :

    fetch('https://sitepoint.com')
    .then(resp=> resp.text()).then(body => console.log(body)) ; 
© www.soinside.com 2019 - 2024. All rights reserved.