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?
express/connect middleware which executes after the response is sent to the client
Asked Answered
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.....
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
See if binding to req.on('end', function() {...});
will work for you.
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.