【问题标题】:NodeJS Express = Catch the sent status code in the responseNodeJS Express = 在响应中捕获发送的状态码
【发布时间】:2020-01-31 21:23:07
【问题描述】:

我将 NodeJS 与 Express 中间件一起使用,我唯一的问题是在全局函数中将确切的已发送状态代码捕获到响应(用于日志)。

使用以下代码:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const router = express.Router();

app.use(bodyParser.json());

router.get('/', (req, res, next) => {
 // ..... SOME LOGIC
 // Suppose that the variable content is coming from the DB
 if (content.length === 0)
 {
    // Status Code : 404
    res.send(404).send("The product cannot be found");
 }
 // Status Code : 200
 res.json(content);
});

app.use((req, res, next) => {
  // Problem : Always returns 200 !
  console.log(res.statusCode);
  next();
});

我正在尝试捕获所有请求,将状态代码记录在中间件 (app.use) 中,但我的问题是 res.statusCode 总是返回 200,即使我给自己发送了 404

问题:

如何在全局函数中捕获确切发送的状态码以便记录它?

谢谢。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    或者,如果你不想做next(new Error),你可以使用res.on("finish",...。这是最后一个触发的事件,将您的代码包装在其中将产生正确的 statusCode

    const express = require("express");
    const bodyParser = require("body-parser");
    
    const app = express();
    const router = express.Router();
    
    app.use(bodyParser.json());
    
    router.get("/", (req, res, next) => {
      //presume 404
      res.send(404).send("The product cannot be found");
    });
    
    app.use((req, res, next) => {
      res.on("finish", function() {
        console.log(res.statusCode); // actual 404
      });
    
      console.log(res.statusCode); // 200 :/ so dont use
      next();
    });
    
    app.listen();
    

    【讨论】:

      【解决方案2】:

      您可能想尝试以下方法 - 使用下一个回调将控制权传递给错误处理程序中间件:

        router.get('/', ( req, res, next) => {
           // ......... SOME LOGIC
           // Suppose that the variable content is coming from the DB
           if (content.length === 0) {
            const err = new Error('The product cannot be found');
            err.status = 404;
            next(err);
           }
           res.json(content);
        });
      
        app.use((err,req, res, next) => {
          console.log(err.status);
        });
      

      【讨论】:

      • “err”变量从何而来?
      • err 来自传递它的 next() 函数
      猜你喜欢
      • 2017-12-21
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多