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

问题描述:

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

I'm using NodeJS with Express middleware, and my only issue is to catch the exact Sent status Code to the response (for logs) in a global function.

使用以下代码:

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 .

I am trying to catch all the requests, to log the status code in a middleware (app.use), but my problem is that the res.statusCode is always returning 200, even when I send myself a 404.

问题:

如何在全局函数中捕获确切发送的状态代码,以便对其进行记录?

How can I catch the exact sent Status Code in a global function so that I can log it?

谢谢.

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

Alternatively, if you don't want to do next(new Error), you can use res.on("finish",.... Which is the last event which fires, wrapping your code in that will yield the correct 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();