首页 > 解决方案 > 如何在 Node 中获取 HTTPS 网站的 HTML 源代码

问题描述

我有以下适用于 Google 的代码片段,但我注意到尝试访问强制 HTTPS 的亚马逊等网站会引发错误 301(永久移动)。我认为问题可能是我使用的是 http 包,但是 HTTPS 包让我感到困惑。如果有人能帮助我,那就太棒了。

var vars = {
    host: “www.google.com”,
    port: 80,
    path: “/index.html”
 }
 http.get(vars, function(res) {
        console.log(res.statusCode);
        res.setEncoding(“utf8”);
        res.on(“data”, function(data) {
             console.log(data);
        }
  })

标签: node.jshttps

解决方案


你可以只使用https.get(). 但是,对于https,您必须使用不同的端口(443)。我更喜欢只传递 URL 并让库为我处理默认端口:

const https = require('https');

https.get("https://www.google.com/index.html", function(res) {
    console.log(res.statusCode);
    res.setEncoding('utf8');
    res.on('data', function(data) {
        console.log(data);
    });
}).on('error', function(err) {
    console.log(err);
});

这可能会在多个data事件中返回数据,因此如果您想要所有数据,则必须手动组合所有数据。

就个人而言,我更喜欢使用基于 Promise 的更高级别的库,并且可以让很多事情变得更简单:

const got = require('got');

got("https://www.google.com/index.html").then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

在许多其他功能中,该got()将自动为您收集整个响应,使用承诺,将遵循重定向,将自动解析 JSON 结果,检查状态并为 4xx 和 5xx 状态提供错误,支持多种身份验证方式等...它比普通的 http/https 库更容易使用。


推荐阅读