How to send a custom http status message in node / express?

前端 未结 9 730
我寻月下人不归
我寻月下人不归 2020-12-12 16:24

My node.js app is modeled like the express/examples/mvc app.

In a controller action I want to spit out a HTTP 400 status with a custom http message. By default the

相关标签:
9条回答
  • 2020-12-12 16:42

    At server side(Express middleware):

    if(err) return res.status(500).end('User already exists.');
    

    Handle at Client side

    Angular:-

    $http().....
    .error(function(data, status) {
      console.error('Repos error', status, data);//"Repos error" 500 "User already exists."
    });
    

    jQuery:-

    $.ajax({
        type: "post",
        url: url,
        success: function (data, text) {
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });
    
    0 讨论(0)
  • 2020-12-12 16:49

    One elegant way to handle custom errors like this in express is:

    function errorHandler(err, req, res, next) {
      var code = err.code;
      var message = err.message;
      res.writeHead(code, message, {'content-type' : 'text/plain'});
      res.end(message);
    }
    

    (you can also use express' built-in express.errorHandler for this)

    Then in your middleware, before your routes:

    app.use(errorHandler);
    

    Then where you want to create the error 'Current password does not match':

    function checkPassword(req, res, next) {
      // check password, fails:
      var err = new Error('Current password does not match');
      err.code = 400;
      // forward control on to the next registered error handler:
      return next(err);
    }
    
    0 讨论(0)
  • 2020-12-12 16:52

    You can use it like this

    return res.status(400).json({'error':'User already exists.'});
    
    0 讨论(0)
提交回复
热议问题