chucklai
chucklai

Reputation: 844

How to debug nodejs.ECONNRESETError: socket hang up

when I send a form with large amount of data file, socket will be abruptly closed by remote server. That's maybe why I got an error of ECONNRESET. How to solve it?

my nodejs code:

Promise((resolve, reject) => {
  let sendOption = {
    method: 'post',
    host: host,
    port: port,
    path: path,
    headers: form.getHeaders(),
    timeout: options.maxTimeout ? 1 * 60 * 60 * 1000 : 2 * 60 * 1000,
  }
  if (options.userName && options.passWord) {
    let auth = new Buffer(options.userName + ':' + options.passWord).toString('base64');
    sendOption.Authorization = 'Basic ' + auth;
  }
  let request = http.request(sendOption, (res) => {
    let body = ''
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end', () => {
      resolve(JSON.parse(body))
    })
  });
  request.on('error', (err) => reject(err));
  request.write(form.getBuffer());
  request.end();
})

Full error:

2020-02-17 19:09:25,570 ERROR 18664 [-/::1/-/14867ms POST /thirdPartUpload] nodejs.ECONNRESETError: socket hang up
    at connResetException (internal/errors.js:570:14)
    at Socket.socketOnEnd (_http_client.js:440:23)
    at Socket.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
code: "ECONNRESET"
name: "ECONNRESETError"
pid: 18664
hostname: PC-HZ20139584
    enter code here

Upvotes: 0

Views: 1353

Answers (1)

O. Jones
O. Jones

Reputation: 108841

POST requests need Content-Length: headers declaring the length of their bodies. In your case you send your POST's body with request.write(form.getBuffer());

An absent or wrong Content-Length: header can look to a server like an attempt to exploit a vulnerability. So servers slam the door (abruptly close the connection) on those requests, which shows up in your client as ECONNRESET.

Try something like this.

const buff = form.getBuffer();
request.setHeader('Content-Length', buff.length);    
request.write(buff);

Upvotes: 1

Related Questions