NodeJS Express = Catch the sent status code in the response

后端 未结 2 1977
盖世英雄少女心
盖世英雄少女心 2021-01-16 04:08

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 follo

2条回答
  •  有刺的猬
    2021-01-16 04:34

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

提交回复
热议问题