Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' }
like image 676
George Katsanos Avatar asked May 20 '26 13:05

George Katsanos


1 Answers

http.request() opens a new tunnel to the server. 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. 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.

like image 103
Jonas Wilms Avatar answered May 22 '26 01:05

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!