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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7772605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:41:02  来源:igfitidea点击:

Get URL Contents in Node.js with Express

node.jsexpress

提问by Andrew M

How would I go about downloading the contents of a URL in Node when using the Express framework? Basically, I need to complete the Facebook authentication flow, but I can't do this without GETing their OAuth Token URL.

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

Normally, in PHP, I'd use Curl, but what is the Node equivalent?

通常,在 PHP 中,我会使用 Curl,但是 Node 等价物是什么?

回答by chovy

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

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

回答by Abdennour TOUMI

The problem that you will front is: some webpage loads its contents using JavaScript. Thus, you needs a package, like After-Loadwhich simulates browser's behavior, then gives you the HTML content of that URL .

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

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

回答by Natesh bhat

Using http way requires way more lines of code for just a simple html page .

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

Here's an efficient way : Use request

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

var request = require("request");

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

Here is the doc for request : https://github.com/request/request

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





2nd Method using fetch with promises :

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

    fetch('https://sitepoint.com')
    .then(resp=> resp.text()).then(body => console.log(body)) ;