node.js 如何指定HTTP错误代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10563644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:41:58  来源:igfitidea点击:

How to specify HTTP error code?

node.jsexpresshttp-status-codes

提问by tech-man

I have tried:

我试过了:

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);
});

but always an error code of 500 is announced.

但总是会公布错误代码 500。

回答by Dan Mandle

Per the Express (Version 4+) docs, you can use:

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

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

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

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

<=3.8

<=3.8

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

回答by Mike P

A simple one liner;

一个简单的一个班轮;

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

回答by Manuel Spigolon

I'd like to centralize the creation of the error response in this way:

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

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})
});

So I have always the same error output format.

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

PS: of course you could create an object to extend the standard errorlike this:

PS:当然你可以创建一个对象来扩展这样的标准错误

const AppError = require('./lib/app-error');
app.get('/test', function(req, res){
  throw new AppError('Detail Message', 500)
});


'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);

回答by Mustafa

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

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

回答by catphive

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.htmlon the other hand lets you do what you are trying to do. So, perhaps trying upgrading to the latest version of express/connect.

与某些(可能是较旧的?)express 版本捆绑在一起的 errorHandler 中间件版本似乎对状态代码进行了硬编码。此处记录的版本:http: //www.senchalabs.org/connect/errorHandler.html另一方面让您可以做您想做的事情。因此,也许尝试升级到最新版本的 express/connect。

回答by Steven Spungin

In express 4.0 they got it right :)

在 express 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')

回答by Ido Ran

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

从我在 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);
}

回答by webarnes

Old question, but still coming up on Google. In the current version of Express (3.4.0), you can alter res.statusCode before calling next(err):

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

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

回答by Rajeev Jayaswal

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

表示不推荐使用的 res.send(body, status)。使用 res.status(status).send(body) 代替

回答by Tarun Rawat

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.

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

This work for me

这对我有用

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