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

标签 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();
});

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

问题:

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

谢谢。

最佳答案

或者,如果您不想执行 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();

关于javascript - NodeJS Express = 在响应中捕获发送的状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204192/

相关文章:

javascript - 如何获取网站中html元素的css、javascript

javascript - 我在将英寸转换为厘米的转换表时遇到问题

javascript - CSS3 和 Javascript : fade text out and then in using the same function

javascript - Node.js:停止执行除单个函数之外的所有代码?

javascript - Socket.io/ARI 错误 : Emit Alert

html - 在 Node.js 中包含 HTML 文件

javascript - 从 Jquery 访问 php 值

javascript - 如何在特定时间跨度内进行具有速率限制的异步 API 调用?

node.js - 如何从当前 Lambda 函数调用另一个 Lambda 函数?

node.js - react /Node 未捕获语法错误 : Unexpected token <