Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
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);
}
});
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();
});