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

2

11

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?

Sinuous answered 20/7, 2013 at 11:34 Comment(0)
S
15

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.....
Steere answered 20/7, 2013 at 17:45 Comment(3)
If I understand correctly, this event will trigger when the client completes sending request/data to server. But what I want is, after calling response.render or response.redirect etc, the middle ware should be executed.Sinuous
No, this event is emitted once the entire request is done, including sending the response. So long as render/redirect call response.end the associated request will emit end.Steere
@SelvarajMA The following approach may be better: https://mcmap.net/q/764107/-how-to-have-a-nodejs-connect-middleware-execute-after-responde-end-has-been-invoked.Corunna
A
4

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

Alabama answered 20/7, 2013 at 12:50 Comment(1)
If I understand correctly, this event will trigger when the client completes sending request/data to server. But what I want is, after calling response.render or response.redirect etc, the middle ware should be executed.Sinuous

© 2022 - 2024 — McMap. All rights reserved.