request: Error: socket hang up

Hi, i know that such issues were created before, but there was a little bit different description.

I tried to perform simple request: send form data. But when i use request module it always throw “socket hang up”.

Below simple test case and results

'use strict';

const request = require('request');
const http = require('http');
const querystring = require('querystring');

const data = {
    xstext: 'I have a some problem about node.js server. What should I do to solve the this problem?',
    spintype: 0,
    removeold: 0,
};

// Using request
request(
    {
        method: 'POST',
        url: 'http://address:9017/',
        form: data,
    },
    (error, responce, body) => {
        if (!error) {
            console.log(body, responce);
            return;
        }
        console.log(error);
    }
);

// Using native http
let postData = querystring.stringify(data);

let options = {
    hostname: 'address',
    port: 9017,
    path: '/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length,
    },
};

let req = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
});

req.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
});

req.write(postData);
req.end();

For request module:

{ [Error: socket hang up] code: 'ECONNRESET' }

For native http:

STATUS: 200
HEADERS: {"content-length":"98","content-type":"text/html","cache-control":"no-cache","connection":"keep-close"}
BODY: Excellent some problem about client. js server. What must i do to solve the particular this issue?
No more data in response.

Loks like it’s really bug in request module.

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Reactions: 6
  • Comments: 84

Commits related to this issue

Most upvoted comments

I have same problem, but add option gzip:true will work.

Somebody save me 👼

In my case I was able to workaround the problem by setting the Connection: keep-alive header.

I see people are getting this error more frequently. In my case it was really simple. What I though was a properly formed URL based on one of my algorithms, was actually malformed. I encourage all of you experiencing this issue to assume the problem is in your code. I assure you, in 98% of the cases the root cause is something mundane that you are taking for granted or overlooking. I have tried all of the above to solve the problem, but in the end, it came down to an extra forward slash.

Wget, curl - success, but request - error.

Node - v6.9.4 Request - 2.79.0

# node req.js
REQUEST { uri: 'http://wtfismyip.com', callback: [Function] }
REQUEST make request http://wtfismyip.com/

{ Error: socket hang up
    at createHangUpError (_http_client.js:254:15)
    at Socket.socketOnEnd (_http_client.js:346:23)
    at emitNone (events.js:91:20)
    at Socket.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9) code: 'ECONNRESET' }

I don’t think that it happens because of the bug you pointed. In our case it appears :

  • Send a request to our backend
  • Backend processes the request
  • Somehow the request is disconnecting without waiting the response and we are getting ECONNRESET
  • We are sure, that our backend server doesn’t break the connection

I’m confused to get this error because in a usual case, our backend server should throw this error or?

NOTE: recording this for others who will probably stumble over this discussion when searching the internet for that particular error message.

As it turns out most of the discussion above misses the point, because the error is not caused by the client site and hence trying different “workarounds” for request will most likely not work. The problem is that the HTTP request socket on the server side runs into the idle timeout, because of a long delay in a background operation, and then closes the socket. That results in the ECONNRESET on the client side.

If you are also responsible for the server side source code and use the express/koa framework then you should disable the idle timeout on the HTTP request socket before initiating the long lasting backend operation. E.g. for an ES6 koa route handler:

ctx => {
    ....
    ctx.socket.setTimeout(0);
    // now trigger the long lasting backend operation
    ....
}

Now my client timeout problem is gone without changing any line in the client code…

Please try request to google.com => hostname: ‘google.com’ to check it work or not. In my case, “hostname” was handle by nginx as proxy and it does not response when receive request with empty body. This code get error:

var http = require("http");
var options = {
  hostname: 'myAddressNginx',
  port: 80,
  path: '/',
  method: 'GET',
  headers: {
    'Content-Type': 'text/html',
    'Content-Length': Buffer.byteLength("")
  }
};

var req = http.request(options, (res) => {
  res.on('data', (chunk) => {console.log("%s", chunk);});
  res.on('end', () => {});
});

// write data to request body
req.write("");
req.end();

This code works

var http = require("http");
var options = {
  hostname: 'myAddressNginx',
  port: 80,
  path: '/',
  method: 'GET',
  headers: {
    'Content-Type': 'text/html',
    'Content-Length': Buffer.byteLength("")
  }
};

var req = http.request(options, (res) => {
  res.on('data', (chunk) => {console.log("%s", chunk);});
  res.on('end', () => {});
});

// write data to request body
req.write("abc");
req.end();

similar issue in native https.request issue see more at here,

add below to request option will bypass (fix) this issue,

agentOptions: {
  ciphers: 'DES-CBC3-SHA'
}

i got caught up and spent the whole afternoon trying to figure it out… was in a complicated environment with several layers of redirect: is this DNS issue? -> no way it's DNS -> definitely DNS -> no it's not till i saw @fractalf 's example, and realized that all these happened only to sites hosted on IIS6 with https

Using ‘http’ instead of ‘https’ protocol solve the issue too.

We ran into this issue after upgrading to a newer nodejs (10.16.3). On client side we used nodejs http agent with keepAlive: true. It looks like the following happened:

  • client uses free socket to do a request
  • in the same time server closes the socket because of keepAliveTimeout setting which has appeared in nodejs version 8

Solution So far we’ve found two solutions:

  1. On the server side disable keepAliveTimeout by setting it equal to 0
  2. Close free sockets in less than keepAliveTimeout value (by default it 5 seconds). The default http agent does not support such a capability (timeout setting does not do it). So we used agentkeepalive lib
const HttpsAgent = require('agentkeepalive').HttpsAgent;

const agent = new HttpsAgent({
    freeSocketTimeout: 4000
});

I have the same bug. The POST works when Content-Length is added to the request. Hope this helps you guys: ‘Content-Length’: Buffer.byteLength(data) //Content-Length is needed for a POST

I’m seeing this too with node 6.6.0. The server I’m connecting to is not sending a Content-Length header in the response, in which case according to the HTTP spec the server should close the stream after sending all data. I suspect this is being misinterpreted as a socket hang up. Making the same request with cURL works fine.

happening with Node v6.9.2.

  get: async function(ctx) {
    let body = await new Promise(function(resolve, reject) {
      return ctx.req.pipe(request('/path/to/my/backend', function(err, res, body) {
        if (err) { return reject(err) }
        resolve(body)
      }))
    })
    return body
  }

try remove ‘accept-encoding’: ‘gzip, deflate’ in the headers solved this.

i have the same issue when i’m testing my routes with chai-http. the absurd is that the first three pass ok!! i’m try to face it all day

here my code:

log("working test")
it("test the /login routes", done => {
   chai
     .request(server)
     .post("/login")
     .send({ })
     .end(function(err, res) {
       expect(err).to.be.null;
       expect(res.status).to.not.equal(404);
       expect(res.body.message).to.not.be.equal("Not Found");
       done();
     });
 });

log(fail test with Error: socket hang up)
 it('test the /getResetCodePassword route', (done)=> {
   chai
     .request(server)
     .patch("/getResetCodePassword")
     .send({ })
     .end( (err,res) => { 
       console.log(err);
       done();
     })
 })

Same issue, node v9.5.0

const https = require("https");
const fs = require("fs");

process.env.NO_PROXY="yourcompany.com";

const options = {
  hostname: "en.wikipedia.org",
  port: 443,
  path: "/wiki/George_Washingtons",
  method: "POST",
  // 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' }

npm configuration:

~/node-training> npm config ls -l
; cli configs
long = true
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.1.0 node/v9.5.0 darwin x64"

; userconfig /Users/katsanos/.npmrc
strict-ssl = false

; default values
access = null
allow-same-version = false
also = null
always-auth = false
audit = true
auth-type = "legacy"
bin-links = true
browser = null
ca = null
cache = "/Users/katsanos/.npm"
cache-lock-retries = 10
cache-lock-stale = 60000
cache-lock-wait = 10000
cache-max = null
cache-min = 10
cafile = undefined
cert = null
cidr = null
color = true
commit-hooks = true
depth = null
description = true
dev = false
dry-run = false
editor = "vi"
engine-strict = false
fetch-retries = 2
fetch-retry-factor = 10
fetch-retry-maxtimeout = 60000
fetch-retry-mintimeout = 10000
force = false
git = "git"
git-tag-version = true
global = false
global-style = false
globalconfig = "/usr/local/etc/npmrc"
globalignorefile = "/usr/local/etc/npmignore"
group = 1493692218
ham-it-up = false
heading = "npm"
https-proxy = null
if-present = false
ignore-prepublish = false
ignore-scripts = false
init-author-email = ""
init-author-name = ""
init-author-url = ""
init-license = "ISC"
init-module = "/Users/katsanos/.npm-init.js"
init-version = "1.0.0"
json = false
key = null
legacy-bundling = false
link = false
local-address = undefined
loglevel = "notice"
logs-max = 10
; long = false (overridden)
maxsockets = 50
message = "%s"
; metrics-registry = null (overridden)
no-proxy = null
node-options = null
node-version = "9.5.0"
offline = false
onload-script = null
only = null
optional = true
otp = null
package-lock = true
package-lock-only = false
parseable = false
prefer-offline = false
prefer-online = false
prefix = "/usr/local"
production = false
progress = true
proxy = null
read-only = false
rebuild-bundle = true
registry = "https://registry.npmjs.org/"
rollback = true
save = true
save-bundle = false
save-dev = false
save-exact = false
save-optional = false
save-prefix = "^"
save-prod = false
scope = ""
script-shell = null
scripts-prepend-node-path = "warn-only"
searchexclude = null
searchlimit = 20
searchopts = ""
searchstaleness = 900
send-metrics = false
shell = "/usr/local/bin/fish"
shrinkwrap = true
sign-git-tag = false
sso-poll-frequency = 500
sso-type = "oauth"
; strict-ssl = true (overridden)
tag = "latest"
tag-version-prefix = "v"
timing = false
tmp = "/var/folders/kn/3cnpbcsx60n4fx_jv6sf4l80_mdkps/T"
umask = 18
unicode = true
unsafe-perm = true
usage = false
user = 356960985
; user-agent = "npm/{npm-version} node/{node-version} {platform} {arch}" (overridden)
userconfig = "/Users/katsanos/.npmrc"
version = false
versions = false
viewer = "man"

EDIT : I was missing req.end() . Works

For me, this is happening while sending a POST request with content-length : 0 in the request headers. I don’t know if this result is reasonable, but at least I think maybe you can try removing each item in headers you added to find out the reason for the problem.

I am still getting this problem.

{ Error: socket hang up
 at createHangUpError (_http_client.js:302:15)
 at Socket.socketOnEnd (_http_client.js:394:23)
 at emitNone (events.js:91:20)
 at Socket.emit (events.js:186:7)
 at endReadableNT (_stream_readable.js:974:12)
 at _combinedTickCallback (internal/process/next_tick.js:74:11)
 at process._tickDomainCallback (internal/process/next_tick.js:122:9) code: 'ECONNRESET' }

Node.js 6.10.0 request 2.72.0

We found the same issue while running some backend integration tests. Our product connects to several network devices using HTTPS. In this scenario, we are establishing several HTTPS connections and executing some POST and GET requests to each device. Since the problem occurred in our test environment, the workaround was to disable the HTTP persistent connections (set HTTP header Connection: close). By doing this, we ask the server to close the connection after delivering the response (HTTP/1.1). However, we lose the benefits of HTTP persistent connections since now each TCP will serve only one request.

+1 Node 6.9.1 request 2.79.0

I have seen this same problem with HapiJS. The issue was a wrong content-length header

Any update about this?. I see the error with botkit 0.2.1.

let req = http.get(options, (res) => {
    ...........
    ...........
}).on('error', function(e) {
        console.error(e);
});

Try this.

+1 Node 6.9.1

This only happens every now and then, when I test my endpoints locally, running many requests in a rather fast manner…

make sure you’re calling the url with the right SSL - either https or http

Finally got this to work for the recaptcha. I had to import and use the https library. Here is the working code:

var https = require(‘https’); var querystring = require(‘querystring’);

var secret = “YOUR_KEY”; var response = RESPONSE_CODE; var postData = “secret=”+secret+“&”+“response=”+response;

// Build the post string from an object var post_data = querystring.stringify({ ‘compilation_level’ : ‘ADVANCED_OPTIMIZATIONS’, ‘output_format’: ‘json’, ‘output_info’: ‘compiled_code’, ‘warning_level’ : ‘QUIET’, ‘js_code’ : postData });

var options = { hostname: ‘www.google.com’, port: 443, path: ‘/recaptcha/api/siteverify’, method: ‘POST’, headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’ //‘content-encoding’: ‘gzip’, //‘Connection’: ‘close’ }, agentOptions: { ciphers: ‘DES-CBC3-SHA’ }
}; var req = https.request(options, function(res) { console.log('Status: ’ + res.statusCode); console.log('Headers: ’ + JSON.stringify(res.headers)); res.setEncoding(‘utf8’); res.on(‘data’, function (body) { console.log('Body: ’ + body); }); }); req.on(‘error’, function(e) { console.log('problem with request: ’ + e.message); }); // write data to request body req.write(postData); req.end();

For me, curl is not working. I found i had set proxy to my command line tool before. It works fine now when i remove proxy.

No luck.

setting ciphers to following didn’t work for me. agentOptions: { ciphers: ‘DES-CBC3-SHA’ }

Hi Guys, I have the same issue. +1 Luckily I use ‘request’ within a 2nd monitoring tool so my issues are minimal. I like node.js a lot, so I’m posting some feedback. I hope my feedback helps a little with your attempts to fix the issue.

The error is now appearing consistently in a high traffic production environments. I can spin up an “exact” replica of the server and the error “never” appears. I can switch endpoints around, and it always ends up the high traffic production environment causes this error for the client. { [Error: socket hang up] code: ‘ECONNRESET’ }.

This began as an intermittent error that I noticed several days ago and after the monitoring service false alarmed too many times… and a heck of a lot of times testing with production test tools that doesn’t use ‘request’ I began searching the web to find this issue here.

Now I have not changed any code/version in over 8 months for this application and am confused to how this can happen out of no where. So… what changed in the ‘request’ world if I didn’t change any client code?

+1 Node 6.9.5

i try to follow all suggest that you say, but this issue does still happen. so sad…