最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 4浏览 0评论

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

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

问题:

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

谢谢。

回答如下:

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

   router.get('/', (req, res, next) => {
     // ..... SOME LOGIC
     // Suppose that the variable content is coming from the DB
     if (content.length === 0)
     {
          const error = 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);
    });

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

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

问题:

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

谢谢。

回答如下:

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

   router.get('/', (req, res, next) => {
     // ..... SOME LOGIC
     // Suppose that the variable content is coming from the DB
     if (content.length === 0)
     {
          const error = 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);
    });
发布评论

评论列表 (0)

  1. 暂无评论