I have tried:
app.get(\'/\', function(req, res, next) {
var e = new Error(\'error message\');
e.status = 400;
next(e);
});
and:
You can use res.send('OMG :(', 404);
just res.send(404);
express deprecated res.send(body, status). Use res.status(status).send(body) instead
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.
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);
}
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);