javascript - NodeJS HTTPS 请求返回 Socket 挂断
问题描述
const https = require("https");
const fs = require("fs");
const options = {
hostname: "en.wikipedia.org",
port: 443,
path: "/wiki/George_Washington",
method: "GET",
// ciphers: 'DES-CBC3-SHA'
};
const req = https.request(options, (res) => {
let responseBody = "";
console.log("Response started");
console.log(`Server Status: ${res.statusCode} `);
console.log(res.headers);
res.setEncoding("UTF-8");
res.once("data", (chunk) => {
console.log(chunk);
});
res.on("data", (chunk) => {
console.log(`--chunk-- ${chunk.length}`);
responseBody += chunk;
});
res.on("end", () => {
fs.writeFile("gw.html", responseBody, (err) => {
if (err) throw err;
console.log("Downloaded file");
});
});
});
req.on("error", (err) => {
console.log("Request problem", err);
});
返回
// Request problem { Error: socket hang up
// at createHangUpError (_http_client.js:330:15)
// at TLSSocket.socketOnEnd (_http_client.js:423:23)
// at TLSSocket.emit (events.js:165:20)
// at endReadableNT (_stream_readable.js:1101:12)
// at process._tickCallback (internal/process/next_tick.js:152:19) code: 'ECONNRESET' }
解决方案
http.request()
打开到服务器的新隧道。它返回一个可写流,允许您将数据发送到服务器,并使用服务器响应的流调用回调。现在您遇到的错误(ECONNRESET
)基本上意味着隧道已关闭。这通常发生在低级别发生错误(非常不可能)或隧道因未收到数据而超时时。在您的情况下,服务器仅在您向其发送内容时才响应,即使它是一个空包,所以您所要做的就是结束流,使其作为空包被刷新到服务器,这会导致它回复:
req.end();
你可能想看看这个request
包,它可以让你避免处理这些低级的事情。
推荐阅读
- python - 根据条件为列名添加后缀
- javascript - 无法弄清楚我的事件监听器出了什么问题
- web - 嵌入链接 Youtube 以在网站上获取缩略图
- c# - 空值从 javascript 传递给控制器
- python - 如何在同一文件夹中安排 Flask 中的模板和静态文件?
- java - PKCS11 类异常中的 C_FindObjectsInit(..)
- asp.net-core - 无法使用 keycloak 从 open-id connect 获取配置
- python - 您如何计算所有故事中每个单词的 TF-IDF 指标
- video - FFmpeg 损坏的连接输出
- r - 在数据框列表中的命名数据框组中执行计算,减少列表,返回 tidyverse 中的列表,R