How to have a NodeJS/connect middleware execute after responde.end() has been invoked?

前端 未结 3 2036
清歌不尽
清歌不尽 2020-12-29 10:27

I would like to achieve something like this:

var c = require(\'connect\');
var app = c();

app.use(\"/api\", function(req, res, next){
    console.log(\"requ         


        
3条回答
  •  春和景丽
    2020-12-29 10:46

    Not sure whether you have found your solution.

    If you want to design a post-processor for the request cycle, you can use a middleware that listens to the "finish" event on the response object. Like this:

    app.use(function(req, res, next){
      res.on('finish', function(){
        console.log("Finished " + res.headersSent); // for example
        console.log("Finished " + res.statusCode);  // for example
        // Do whatever you want
      });
      next();
    });
    

    The function attached to the "finish" event will be executed after the response is written out (which means the NodeJS has handed off the response header and body to the OS for network transmission).

    I guess this must be what you want.

提交回复
热议问题