NodeJS HTTPs请求返回Socket挂断

时间:2018-07-08 10:47:40

标签: javascript node.js https

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' }

1 个答案:

答案 0 :(得分:1)

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

 req.end();

您可能想看看request软件包,它使您避免处理这些低级的事情。

相关问题