小编You*_*sef的帖子

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

javascript node.js express

1
推荐指数
1
解决办法
1879
查看次数

标签 统计

express ×1

javascript ×1

node.js ×1