【问题标题】:How to specify HTTP error code using Express.js?如何使用 Express.js 指定 HTTP 错误代码?
【发布时间】:2012-05-20 18:36:32
【问题描述】:

我试过了:

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

和:

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

但总是宣布错误代码 500。

【问题讨论】:

标签: node.js express http-status-codes


【解决方案1】:

异步方式:

  myNodeJs.processAsync(pays)
        .then((result) => {
            myLog.logger.info('API 200 OK');
            res.statusCode = 200;
            res.json(result);
            myLog.logger.response(result);
        })
        .fail((error) => {
            if (error instanceof myTypes.types.MyError) {
                log.logger.info(`My Custom Error:${error.toString()}`);
                res.statusCode = 400;
                res.json(error);
            } else {
                log.logger.error(error);
                res.statusCode = 500;
                // it seems standard errors do not go properly into json by themselves
                res.json({
                    name: error.name,
                    message: error.message
                });
            }
            log.logger.response(error);
        })
        .done();

【讨论】:

    【解决方案2】:

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

    改用res.status(status).send(body)

    【讨论】:

      【解决方案3】:

      我试过了

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

      ..但它给了我错误

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

      这对我有用

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

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

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

          PS:当然你可以像这样为extend the standard error 创建一个对象:

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

          【讨论】:

          • 很好的解决方案,但这给了我 UnhandledPromiseRejectionWarning 错误。如何确保错误在我们的错误中间件中得到处理
          • async/await 不支持开箱即用 express,试试这个github.com/fastify/fastify
          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

            一个简单的班轮;

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

            【讨论】:

              【解决方案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);
              }
              

              【讨论】:

                【解决方案9】:

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

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

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

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

                【讨论】:

                • +1 用于使用最新版本的 API。如果您想发送更多信息,只需链接:res.status(400).json({ error: 'message' })
                • @Mikel 如果您没有响应变量,则无法发送响应。
                • 现在都弃用了,你应该使用res.sendStatus(401);
                • 这个回复如果以res.send('Then you shall die')结尾会更完整。
                • @Cipi 你有那个来源吗?该文档并未表明 .status() 已弃用。 .sendStatus() 只是.status(code).send(codeName) 的简写,其中codeName 是给定code 的标准HTTP 响应文本。
                【解决方案10】:

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

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

                【讨论】:

                • 下一步做什么?
                • next 正在调用下一个处理程序,该处理程序在 express.js 中通常会尝试呈现错误页面。
                【解决方案11】:

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

                【讨论】:

                  【解决方案12】:

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

                  【讨论】:

                  • 但是我想把错误码发送到eventHandler中间件,所以要显示express的自定义错误页面。
                  • 对于 2016 年阅读本文的任何人:根据 Express 4.x,res.send(404) 已弃用。现在是res.sendStatus(404)expressjs.com/en/api.html#res.sendStatus
                  猜你喜欢
                  • 2011-12-31
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-01-10
                  • 2010-10-12
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多