首页 > 解决方案 > 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' }

标签: javascriptnode.jshttps

解决方案


http.request()打开到服务器的新隧道。它返回一个可写流,允许您将数据发送到服务器,并使用服务器响应的流调用回调。现在您遇到的错误(ECONNRESET)基本上意味着隧道已关闭。这通常发生在低级别发生错误(非常不可能)或隧道因未收到数据而超时时。在您的情况下,服务器仅在您向其发送内容时才响应,即使它是一个空包,所以您所要做的就是结束流,使其作为空包被刷新到服务器,这会导致它回复:

 req.end();

你可能想看看这个request包,它可以让你避免处理这些低级的事情。


推荐阅读