Selvaraj M A
Selvaraj M A

Reputation: 3136

express/connect middleware which executes after the response is sent to the client

Is it possible to write a middleware which executes after the response is sent to a client or after the request is processed and called just before sending the response to client?

Upvotes: 11

Views: 7301

Answers (2)

Morgan ARR Allen
Morgan ARR Allen

Reputation: 10678

pauljz gave the basic method but to expand on that here is an example of middleware

module.exports = function() {
  return function(req, res, next) {
    req.on("end", function() {
      // some code to be executed after another middleware
      // does some stuff
    });
    next(); // move onto next middleware
  }
}

In your main app

expressApp.use(require("./doneMiddleware"));
expressApp.use(express.logger());
expressApp.use(express.static.....

Upvotes: 15

pauljz
pauljz

Reputation: 10901

See if binding to req.on('end', function() {...}); will work for you.

Upvotes: 4

Related Questions