如何指定HTTP错误代码?

tec*_*man 143 http-status-codes node.js express

我试过了:

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

和:

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

但总是宣布错误代码为500.

Dan*_*dle 264

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

res.status(400);
res.send('None shall pass');
Run Code Online (Sandbox Code Playgroud)

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

<= 3.8

res.statusCode = 401;
res.send('None shall pass');
Run Code Online (Sandbox Code Playgroud)

  • +1使用最新版本的API.如果你想发送更多信息,只需链:`res.status(400).json({error:'message'})` (32认同)
  • 现在这一切都已弃用,您应该使用 `res.sendStatus(401);`。 (2认同)
  • @Cipi 你有来源吗?文档并未表明 `.status()` 已被弃用。`.sendStatus()` 只是 `.status(code).send(codeName)` 的简写,其中 `codeName` 是给定 `code` 的标准 HTTP 响应文本。 (2认同)

Mik*_*e P 69

一个简单的衬垫;

res.status(404).send("Oh uh, something went wrong");
Run Code Online (Sandbox Code Playgroud)


Mus*_*afa 15

您可以使用res.send('OMG :(', 404);res.send(404);

  • 对于2016年阅读此内容的人:根据Express 4.x,不推荐使用`res.send(404)`.它现在是`res.sendStatus(404)`.http://expressjs.com/en/api.html#res.sendStatus (10认同)

Man*_*lon 13

我想以这种方式集中创建错误响应:

app.get('/test', function(req, res){
  throw {status: 500, message: 'detailed message'};
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500).json({status: err.status, message: err.message})
});
Run Code Online (Sandbox Code Playgroud)

所以我总是有相同的错误输出格式.

PS:当然你可以创建一个对象来扩展标准错误,如下所示:

const AppError = require('./lib/app-error');
app.get('/test', function(req, res){
  throw new AppError('Detail Message', 500)
});
Run Code Online (Sandbox Code Playgroud)
'use strict';

module.exports = function AppError(message, httpStatus) {
  Error.captureStackTrace(this, this.constructor);
  this.name = this.constructor.name;
  this.message = message;
  this.status = httpStatus;
};

require('util').inherits(module.exports, Error);
Run Code Online (Sandbox Code Playgroud)


cat*_*ive 11

与一些(可能是较旧的?)版本捆绑捆绑的errorHandler中间件的版本似乎具有硬编码的状态代码.此处记录的版本:http://www.senchalabs.org/connect/errorHandler.html允许您执行您要执行的操作.所以,也许尝试升级到最新版本的express/connect.


Ste*_*gin 10

在快递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')
Run Code Online (Sandbox Code Playgroud)


web*_*nes 8

老问题,但仍然出现在谷歌上.在当前版本的Express(3.4.0)中,您可以在调用next(err)之前更改res.statusCode:

res.statusCode = 404;
next(new Error('File not found'));
Run Code Online (Sandbox Code Playgroud)


Ido*_*Ran 8

从我在Express 4.0中看到的,这对我有用.这是身份验证所需中间件的示例.

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);
}
Run Code Online (Sandbox Code Playgroud)


Raj*_*wal 8

Express 已弃用res.send(body, status)

使用res.status(status).send(body)res.sendStatus(status)代替


小智 5

我试过

res.status(400);
res.send('message');
Run Code Online (Sandbox Code Playgroud)

..但它给了我错误

(节点:208)UnhandledPromiseRejectionWarning:错误:发送后无法设置标头。

这对我有用

res.status(400).send(yourMessage);
Run Code Online (Sandbox Code Playgroud)