NodeJS Express = Catch the sent status code in the response

后端 未结 2 1984
盖世英雄少女心
盖世英雄少女心 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:36

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

提交回复
热议问题