node.js - 如何在 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);
}
})
解决方案
你可以只使用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 库更容易使用。
推荐阅读
- c# - ASP.NET Core 单元测试在测试控制器问题响应时抛出 Null Exception
- ansible - 错误消息中存在字符串时忽略失败
- php - Facebook集成:如何实现非规范元数据抓取
- npm - IBM uDeploy 无法从工件中检索 npm 版本
- node.js - 错误:BotFrameworkAdapter.processActivity():401 错误
- python - 为什么我不能使用 paramiko 在远程服务器上运行“support show db-status free %”?
- iexpress - iexpress设置提取路径?
- php - 更新用户的详细信息并显示相同
- nlog - 为什么 Nlog 每隔几分钟归档一次文件?
- javascript - 无法将状态中的字符串数组映射到 React Native Picker 中的 Picker.item