title: nodejs https Error: socket hang up with localhost
body: <p>I have this small code snippet that targets an endpoint hosted on localhost</p>
  
  <pre><code>var https = require('https');
  
  var options = {
    hostname: 'localhost',
    port: 443,
    path: '/',
    method: 'GET',
    agent: false
  };
  
  var req = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);
    res.on('data', function(d) {
      process.stdout.write(d);
    });
  });
  req.end();
  
  req.on('error', function(e) {
    console.error(e);
  });
  </code></pre>
  
  <p>and I always get the error:</p>
  
  <p>{ [Error: socket hang up] code: 'ECONNRESET', sslError: undefined }</p>
  
  <p>It seems that the request is not even received by the endpoint because the it's not captured by it and there is no timeout happening.</p>
  
  <p>If I try a request like https:// localhost from the browser, it's sent successfully.</p>
  
  <p>If I just change the host in the code to something like encrypted.google.com, it works successfully as well.</p>
  
  <p>Anyone knows why this might happen ?</p>
  
  <p><strong>Edit</strong>: I've also tried adding the same headers sent by the browser like accept, user-agent .. etc, but still not working</p>
  
  <p><strong>Edit2</strong>: this is the stack trace that appeared when I logged it:</p>
  
  <pre><code>Error: socket hang up
  at SecurePair.error (tls.js:1013:23)
  at EncryptedStream.CryptoStream._done (tls.js:705:22)
  at CleartextStream.read [as _read] (tls.js:496:24)
  at CleartextStream.Readable.read (_stream_readable.js:320:10)
  at EncryptedStream.onCryptoStreamFinish (tls.js:301:47)
  at EncryptedStream.g (events.js:180:16)
  at EncryptedStream.EventEmitter.emit (events.js:117:20)
  at finishMaybe (_stream_writable.js:360:12)
  at endWritable (_stream_writable.js:367:3)
  at EncryptedStream.Writable.end (_stream_writable.js:345:5)
  </code></pre>