Request: Error: socket hang up

Created on 31 Jan 2016  ·  77Comments  ·  Source: request/request

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.

Not enough info (see CONTRIBUTING.md)

Most helpful comment

Somebody save me :angel:

All 77 comments

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

What version of node.js are you using? We're seeing occasional ECONNRESET exceptions after upgrading from 0.10 to 0.12. From digging through the node.js bugs it looks like this might have been broken in 0.12 and fixed afterwards.

Same issue here. Any updates ? I'm using node.js 4.2.2 and I am getting periodic (3-4 times per minute) ECONNRESET error.

Hi @aymeba it looks like the first 4.x version which has this fix is 4.4.0.

Look for commits titled http: handle errors on idle sockets. There are a bunch of different commits with this title, since it was applied to different branches.

Nevermind, I got confused and was talking about an ECONNRESET bug in node.js (#3595).

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?

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

I am having a similar issue. I have done hours of research, testing and debugging. In my case posting to the same restapi via Postman the end-point works fine. Making the request via the native NodeJS http.request call fail. All headers, and payload (body) are the same. (except I don't have the postman-token in the headers)

Full disclosure, I am using restify for my server.

In case you using restify on the server side, it would help to enable the auditer, that should provide some hint on what is going on. Also, make sure you are setting the right "Content-Type" in your request so the server knows what to expect. I've seen this error when the server is misunderstanding the request, so providing the content type will help.

Any update on this issue? I still see this issue happening with Node v5.0.0. I see it throws error exactly after 45 secs from the time the request is made.

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

i want to make a request for a subscription and notification thanks...

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
  }

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.

+1
Node 6.9.4
request 2.79.0

Works fine with curl
The url I try to get returns header Content-Length

+1
Node 6.9.1
request 2.79.0

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

Having the same problem. Interestingly it seems to be independent of the request version as the same code works for me in 6.4.0, but breaks in 6.9.2 (these are just the 2 nodejs versions I happen to have installed).

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

@dieseldjango Thanks for the suggestion. Didn't solve my case though.

Here is a site that gives this error, for reproduction:

{ request: 
   { debugId: 1,
     uri: 'https://www.deal.no/',
     method: 'GET',
     headers: 
      { Connection: 'keep-alive',
        host: 'www.deal.no',
        'accept-encoding': 'gzip, deflate' } } }
error:  Error: socket hang up
    at TLSSocket.onHangUp (_tls_wrap.js:1111:19)
    at TLSSocket.g (events.js:291:16)
    at emitNone (events.js:91:20)
    at TLSSocket.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)

..using request-debug for debugging the headers sent

Isn't this resolved yet? It was working fine like two weeks ago and i'm now getting this error
{ [Error: socket hang up] code: 'ECONNRESET', response: undefined }
node -v 4.4.7

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

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.

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

If it helps anyone I eventually worked around the issue by using require('child_process').exec to call curl. Make sure you properly sanitize your inputs if they're coming from userland.

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

+1
Node 6.9.5

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.1

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

We are also facing same issue with node4 and node6. working fine with node0.12.

Please help on fixing this.

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

No luck.

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

@aganapan what's the url you were requesting? My solution will only fix issues related to website hosting on IIS6 + TLS1.0. There could be other issues that result in similar error msg.

I had the same problem. I used ngrok and looked at the RAW request. Turned out that there was a e2808b non printable character appended to the user input. Most probably copy/paste. I used encodeURIComponent() on that user provided URI part and the problem vanished.

I had the same problem.

  • node V6.9.5
  • request V2.69.0

@danielkhan I have used the encodeURIComponent method;

// this is request
{
    "request": {
        "debugId": 5,
        "uri": "https://xxx.cdn.cn/js/information_main_27d1838a.js",
        "method": "GET",
        "headers": {
            "user-agent": "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36",
            "host": "xxx.cdn.cn"
        }
    }
}

{
    "response": {
        "debugId": 5,
        "headers": {
            "expires": "Sat, 15 Apr 2017 11:01:16 GMT",
            "date": "Thu, 16 Mar 2017 11:01:16 GMT",
            "content-type": "application/x-javascript; charset=utf-8",
            "content-length": "49785",
            "last-modified": "Sun, 12 Mar 2017 14:30:49 GMT",
            "cache-control": "max-age=2592000",
            "access-control-allow-origin": "*",
            "accept-ranges": "bytes",
            "age": "19",
            "x-cache": "HIT from www.matocloud.com",
            "connection": "close",
            "alt-svc": "h2=\":443\""
        },
        "statusCode": 200
    }
}

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.

chrome is blocking this DES-CBC3-SHA solution

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.

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

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

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:

javascript 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...

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

It's also proxy issue in my case. After reset http_proxy and https_proxy, the issue is gone.

I had the same issue.

For curl:
HTTP/1.1 200 OK

For native http module:
{ [Error: socket hang up] code: 'ECONNRESET' }

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

The reason was in response, particularly in wrong syntax of http protocol.
\n symbol was after every header, but must be \r\n, and after last header - \r\n\r\n.

When it was fixed, the error disappeared.

May be it will be useful and save time for somebody.

I had the same problem. In my case I set User-Agent in headers in request options and problem is gone.

Having the same issue with Node 8.x

+1
Node 8.1.2
"request": "=2.81.0"

{
    "method": "GET",
    "json": true,
    "uri": "http://www.bb.com/xxxxxxxxxxx",
    "baseUrl": null,
    "headers": {
        "cookie": "yyyyy",
        "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60"
    },
    "qs": {
        "app_version": "1.9.8.8",
        "env": "prod"
    }
}

//res
Error: socket hang up
InternalServerError: Internal Server Error

// setting
var _request = require('request').defaults({
        forever      : true,
        maxRedirects : 8
    }),

I got the same error, but a little bit different, my situation is like this.
testapp -> api A -> api B
-> means request
test app get the hang up error when A request B very slowly and finally get an 500 error from B (the error is handled in api A).
I'm sure it's not a time out issue, since api A do a lot of things and always return response very slow, but no error.
Now i'm really confused how the express and request works, the 500 error is already handled by api A and has other actions follow up. why the test app will still get socket hang up error?

I'm also running into this issue in the latest node (8.6) as well as with the latest 7.x release. Details are here if anyone wants to take a stab at it: https://stackoverflow.com/questions/46666079/node-js-http-get-econnreset-error-on-read

Please let me know if I can provide any additional information!

Having the same issue with Node 6.10.0

Another possible explanation: you are sending more data in HTTP body than specified in Content-Length header

+1
Node 8.6.0

To fix the issue you should:
1-Add process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
2-Upgrade zone.js to v0.7.4

I had the same problem and the resolution was to use environment variable NO_PROXY="yourcompany.com" as well as strictSSL:false, as our request was being made to internal company url and was attempting to use proxy server. You can use process.env.NO_PROXY="yourcompany.com" programmatically.

+1
Node 8.8.1

at createHangUpError (_http_client.js:329:15)
at Socket.socketOnEnd (_http_client.js:421:23)
at emitNone (events.js:110:20)
at Socket.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9) code: 'ECONNRESET' }

appears the issue on my end was that Vagrant was "occupying" the port and sending a TCP packet with a FIN flag immediately following my GET request although it's still unclear why chrome and postman had no problem working around this - perhaps they have some added resilience

I had this problem, GZIP was on, Keep alive was on too.
The problem vanished after adding packages.

const zlib = require('zlib'); // for GZIP
const http = require('http');
const https = require('https');

Same problem - fixed by changing the URL from localhost to the actual IP of the host machine just a FYI

Still having this issue.... No apparent reason.

info:  Error: socket hang up
    at createHangUpError (_http_client.js:345:15)
    at Socket.socketOnEnd (_http_client.js:437:23)
    at emitNone (events.js:110:20)
    at Socket.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1059:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)

hi, I do not know if you solved this problem yet, but I had solved this tody, when I debug, I find,

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

if you remote server is start by koa(or another nodejs server), and the data is {}, the postData by stringify function transform to {}, but the koa server get the {} will throw the parser error, so this request will throw error by

Error: socket hang up
    at createHangUpError (_http_client.js:345:15)
    at Socket.socketOnEnd (_http_client.js:437:23)
    at emitNone (events.js:110:20)
    at Socket.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1059:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)

so I had do this : __postData = postData === '{}' ? '' : postData__

hope it's can help you

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.

when i change 'GET' to 'POST', fix it. but dont know why, i fix it from https://cnodejs.org/topic/57a6c35282e6ea4870ecd3f2, someone said if you use 'GET', the code cant run res.on('data', cb)

@LvChengbin I was also facing the same problem on POST request. Replacing Content-Length : 0with actual length of the body worked for me.

Somebody save me :angel:

I have also the same problem in bode v.8.9

{ Error: socket hang up
at createHangUpError (_http_client.js:331:15)
at Socket.socketOnEnd (_http_client.js:423:23)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) code: 'ECONNR
ESET' }

my code is below.

let request=require("request");
request({
url: "http://192.168.31.29:3019/tactics/createMediaHotTotal20",
method: "GET",
json: true,
headers: {
"content-type": "application/json"
},
}, function (error, response, body) {
if (error) {
console.log(error)
} else {
resolve(body);
}
})

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



md5-988987fef0feed585119ccc2fe5450ba



~/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

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

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

SAVE MY DAY!

I dig it a little bit.
I have a rear once in a week issue with request when send POST to nodejs server.
After going dipper, I found that nodejs just hang connection if request is malformed.

Looks like some rear bug happens when POST request get passed into http.request

In my case body was send without last symbols and MAYBE it was due to miscalculation of Content-Length in setContentLength()

Using 'http' instead of 'https' protocol solve the issue too.

This is very frustrating. I don't have control over the server but I can't do POST from Nodejs (using request or superagent), but can do curl or Postman successfully. Even crazier, the call would succeed if I pause using debugger on the request statement, and continue.

In my case just removed the 'Host' header, solved.

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
});
let req = http.get(options, (res) => {
    ...........
    ...........
}).on('error', function(e) {
        console.error(e);
});

Try this.

We are facing a similar issue - currently, we are using 6.11.x but we tried node 10 but does not help.

We even tried upgrading request module + adding all suggestions provided but no help.

Any other ideas or help in troubleshooting.

we are able to resolve this issue - our API gateway had a timeout setting that causing this issue. thanks for looking into it.

we are able to resolve this issue - our API gateway had a timeout setting that causing this issue. thanks for looking into it.

Hi, can you tell me what kind of timeout setting lead to this problem

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

```

Was this page helpful?
0 / 5 - 0 ratings