简体   繁体   English

NodeJS HTTPs请求返回Socket挂断

[英]NodeJS HTTPs request returns Socket Hang up

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);
});

returns 回报

// 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() opens a new tunnel to the server. http.request()打开到服务器的新隧道。 It returns a Writable stream which allows you to send data to the server, and the callback gets called with the stream that the server responds with. 它返回一个可写流,该流允许您将数据发送到服务器,并使用服务器响应的流调用回调。 Now the error you encountered ( ECONNRESET ) basically means that the tunnel was closed. 现在,您遇到的错误( ECONNRESET )基本上意味着隧道已关闭。 That usually happens when an error occured on a low level (very unlikely) or the tunnel timed out because no data was received. 当错误发生在较低级别(极不可能)或隧道由于未接收到数据而超时时,通常会发生这种情况。 In your case the server only responded when you sent something to it, even if it was an empty package, so all you have to do is to end the stream, causing it to get flushed as an empty packet to the server, which causes it to respond: 在您的情况下,服务器仅在向您发送了一些东西时才响应,即使它是一个空包,因此您所要做的就是结束流,导致流作为空包刷新到服务器,这导致它回复:

 req.end();

You might want to have a look at the request package which allows you to avoid dealing with such low-level things. 您可能想看看request包,它使您避免处理这些低级的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM