Node.js POST causes [Error: socket hang up] code:

2020-01-27 03:19发布

I created a sample to post data to a rest services and I found out that when I have non-ascii or non-latin character (please see data.firstName), my post request using TEST-REST.js will throw

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

// TEST-REST.js
var http = require('http');

var data = JSON.stringify({
  firstName: 'JoaquÌn',
});

var options = {
  host: '127.0.0.1',
  port: 3000,
  path: '/users',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

var req = http.request(options, function(res) {
  var result = '';

  res.on('data', function(chunk) {
    result += chunk;
  });

  res.on('end', function() {
    console.log(result);
  });
});

req.on('error', function(err) {
  console.log(err);
});

req.write(data);
req.end();

and on my rest services, it throw me error like this:

SyntaxError: Unexpected end of input Sun Sep 08 2013 23:25:02 GMT-0700 (PDT) -     at Object.parse (native)
    at IncomingMessage.<anonymous> (/Volumes/Data/Program_Data/GitHub/app/node_modules/express/node_modules/connect/lib/middleware/json.js:66:27) info    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at _stream_readable.js:920:16 : - - - [Mon, 09 Sep 2013 06:25:02 GMT] "POST /users HTTP/1.1" 400 - "-" "-"
    at process._tickDomainCallback (node.js:459:13)

if I replace firstName value from 'JoaquÌn' to 'abc', everything works just fine. I think I'm missing something to support or escape to make it work.

does anyone have any idea how I solve this problem? I also tried following: require('querystring').escape(model.givenName), and it works but I'm not happy with it.

UPDATED I found out that if I comment out: app.use(express.bodyParser());, the error disappears.

2条回答
小情绪 Triste *
2楼-- · 2020-01-27 03:47

This is node's issue, not express's issue. https://github.com/visionmedia/express/issues/1749

to resolve, change from

'Content-Length': data.length

to

'Content-Length': Buffer.byteLength(data)

RULE OF THUMB

Always use Buffer.byteLength() when you want to find the content length of strings

UPDATED

We also should handle error gracefully on server side to prevent crashing by adding middleware to handle it.

app.use(function (error, req, res, next) {
  if (!error) {
    next();
  } else {
    console.error(error.stack);
    res.send(500);
  }
});
查看更多
够拽才男人
3楼-- · 2020-01-27 04:13

The problem is that if you don't handle this error and keep the server alive, this remote crash exploit could be used for a DOS attack. However, you can handle it and continue on, and still shut down the process when unhandled exceptions occur (which prevents you from running in undefined state -- a very bad thing).

The connect module handles the error and calls next(), sending back an object with the message body and status = 400. In your server code, you can add this after express.bodyParser():

var exit = function exit() {
  setTimeout(function () {
    process.exit(1);
  }, 0);
};

app.use(function (error, req, res, next) {
  if (error.status === 400) {
    log.info(error.body);
    return res.send(400);
  }

  log.error(error);
  exit();
});
查看更多
登录 后发表回答