Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: socket hang up #2047

Open
Areks opened this issue Jan 30, 2016 · 72 comments

Comments

@Areks
Copy link

commented Jan 30, 2016

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.

@tiodot

This comment has been minimized.

Copy link

commented Feb 2, 2016

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

@drewfish

This comment has been minimized.

Copy link

commented Mar 9, 2016

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.

@aymeba

This comment has been minimized.

Copy link

commented Mar 14, 2016

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.

@drewfish

This comment has been minimized.

Copy link

commented Mar 14, 2016

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

@aymeba

This comment has been minimized.

Copy link

commented Mar 14, 2016

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?

@juanpablopizarro

This comment has been minimized.

Copy link

commented Jun 24, 2016

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

@gochinj

This comment has been minimized.

Copy link

commented Jul 29, 2016

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.

@nsilva

This comment has been minimized.

Copy link

commented Aug 15, 2016

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.

@murali0286

This comment has been minimized.

Copy link

commented Oct 12, 2016

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.

@mllanes

This comment has been minimized.

Copy link

commented Nov 3, 2016

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

@roddrec23

This comment has been minimized.

Copy link

commented Dec 4, 2016

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

@wuwb

This comment has been minimized.

Copy link

commented Jan 3, 2017

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
  }
@dieseldjango

This comment has been minimized.

Copy link

commented Jan 6, 2017

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.

@fractalf

This comment has been minimized.

Copy link

commented Jan 10, 2017

+1
Node 6.9.4
request 2.79.0

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

@atMari

This comment has been minimized.

Copy link

commented Jan 13, 2017

+1
Node 6.9.1
request 2.79.0

@extensionsapp

This comment has been minimized.

Copy link

commented Jan 13, 2017

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

This comment has been minimized.

Copy link

commented Jan 13, 2017

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

@dieseldjango

This comment has been minimized.

Copy link

commented Jan 13, 2017

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

@fractalf

This comment has been minimized.

Copy link

commented Jan 16, 2017

@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

@hamxabaig

This comment has been minimized.

Copy link

commented Jan 25, 2017

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

@wuwb

This comment has been minimized.

Copy link

commented Jan 26, 2017

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

@gochinj

This comment has been minimized.

Copy link

commented Jan 26, 2017

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.

@kazaff

This comment has been minimized.

Copy link

commented Feb 7, 2017

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

@Vanit

This comment has been minimized.

Copy link

commented Feb 7, 2017

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.

@itsay

This comment has been minimized.

Copy link

commented Feb 13, 2017

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

This comment has been minimized.

Copy link

commented Feb 13, 2017

+1
Node 6.9.5

@vognition

This comment has been minimized.

Copy link

commented Feb 16, 2017

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?

@BenSower

This comment has been minimized.

Copy link

commented Feb 22, 2017

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

@illya13

This comment has been minimized.

Copy link

commented Oct 31, 2017

+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' }
@jpollard-cs

This comment has been minimized.

Copy link

commented Nov 2, 2017

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

@dotbloup

This comment has been minimized.

Copy link

commented Nov 21, 2017

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');
@markbarton

This comment has been minimized.

Copy link

commented Nov 30, 2017

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

@tsirolnik

This comment has been minimized.

Copy link

commented Dec 12, 2017

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)
@renminghao

This comment has been minimized.

Copy link

commented Jan 3, 2018

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

@LvChengbin

This comment has been minimized.

Copy link

commented Jan 18, 2018

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.

@dumplings

This comment has been minimized.

Copy link

commented Feb 2, 2018

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)

@ahmedfouzan

This comment has been minimized.

Copy link

commented Feb 6, 2018

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

@lfreneda

This comment has been minimized.

Copy link

commented Apr 3, 2018

Somebody save me 👼

@YeDongaidiiqu

This comment has been minimized.

Copy link

commented Apr 26, 2018

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

@gkatsanos

This comment has been minimized.

Copy link

commented Jul 8, 2018

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

@ablade

This comment has been minimized.

Copy link

commented Oct 17, 2018

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

@HuChundong

This comment has been minimized.

Copy link

commented Oct 26, 2018

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

SAVE MY DAY!

udacimak added a commit to udacimak/udacimak that referenced this issue Nov 7, 2018
kika added a commit to kika/firebase-tools that referenced this issue Jan 8, 2019
Resolution to firebase#1095
According to the advice given in the thread request/request#2047
@kika kika referenced this issue Jan 9, 2019
@Gormartsen

This comment has been minimized.

Copy link

commented Mar 8, 2019

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

@and-kost

This comment has been minimized.

Copy link

commented Jun 5, 2019

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

@cactusme

This comment has been minimized.

Copy link

commented Jun 19, 2019

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.

@wjsilva85

This comment has been minimized.

Copy link

commented Jul 19, 2019

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

@davoam

This comment has been minimized.

Copy link

commented Sep 18, 2019

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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
You can’t perform that action at this time.