我试过:

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

and:

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

但是总会出现一个500的错误代码。


当前回答

在特快4.0中,他们做对了:)

res.sendStatus(statusCode)
// Sets the response HTTP status code to statusCode and send its string representation as the response body.

res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')

//If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.

res.sendStatus(2000); // equivalent to res.status(2000).send('2000')

其他回答

根据Express (Version 4+)文档,您可以使用:

res.status(400);
res.send('None shall pass');

http://expressjs.com/4x/api.html#res.status

< = 3.8

res.statusCode = 401;
res.send('None shall pass');

我建议使用Boom包来处理http错误代码的发送。

我试着

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

..但它给了我错误:

(节点:208)UnhandledPromiseRejectionWarning:错误:不能设置报头 在发送之后。

这对我很有用

res.status(400).send(yourMessage);

简单的一行;

res.status(404).send("Oh uh, something went wrong");

老问题了,但谷歌仍在播。在Express的当前版本(3.4.0)中,你可以在调用next(err)之前修改res.statusCode:

res.statusCode = 404;
next(new Error('File not found'));