NodeJS Express = 在响应中捕获发送的状态代码

You*_*sef 1 javascript node.js express

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

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

问题 :

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

谢谢。

Law*_*one 5

或者,如果您不想这样做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();
Run Code Online (Sandbox Code Playgroud)