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

后端 未结 2 1943
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 04:25

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-

相关标签:
2条回答
  • 2020-11-30 04:44

    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);
      }
    });
    
    0 讨论(0)
  • 2020-11-30 05:00

    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();
    });
    
    0 讨论(0)
提交回复
热议问题