NodeJS Express = Catch the sent status code in the response

∥☆過路亽.° 提交于 2020-08-19 10:32:43

问题


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.

Using the following code :

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

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.

Question :

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

Thank you.


回答1:


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



回答2:


you might want to try something like below - use the next callback to pass control to the error handler middleware:

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


来源:https://stackoverflow.com/questions/58204192/nodejs-express-catch-the-sent-status-code-in-the-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!