How to specify HTTP error code?

后端 未结 11 2603
余生分开走
余生分开走 2020-12-02 13:48

I have tried:

app.get(\'/\', function(req, res, next) {
    var e = new Error(\'error message\');
    e.status = 400;
    next(e);
});

and:

相关标签:
11条回答
  • 2020-12-02 14:32

    You can use res.send('OMG :(', 404); just res.send(404);

    0 讨论(0)
  • 2020-12-02 14:40

    express deprecated res.send(body, status). Use res.status(status).send(body) instead

    0 讨论(0)
  • 2020-12-02 14:41

    The version of the errorHandler middleware bundled with some (perhaps older?) versions of express seems to have the status code hardcoded. The version documented here: http://www.senchalabs.org/connect/errorHandler.html on the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.

    0 讨论(0)
  • 2020-12-02 14:43

    From what I saw in Express 4.0 this works for me. This is example of authentication required middleware.

    function apiDemandLoggedIn(req, res, next) {
    
        // if user is authenticated in the session, carry on
        console.log('isAuth', req.isAuthenticated(), req.user);
        if (req.isAuthenticated())
            return next();
    
        // If not return 401 response which means unauthroized.
        var err = new Error();
        err.status = 401;
        next(err);
    }
    
    0 讨论(0)
  • 2020-12-02 14:44

    I tried

    res.status(400);
    res.send('message');
    

    ..but it was giving me error:

    (node:208) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.

    This work for me

    res.status(400).send(yourMessage);
    
    0 讨论(0)
提交回复
热议问题