ExpressJS middleware req, res, next have hooks like .on and .pipe.
But I'm looking for hooks for the app.get and app.post methods.
app.use() and middleware can be used for "before" and a combination of the 'close' and 'finish' events can be used for "after."
app.use(function (req, res, next) {
function afterResponse() {
res.removeListener('finish', afterResponse);
res.removeListener('close', afterResponse);
// action after response
}
res.on('finish', afterResponse);
res.on('close', afterResponse);
// action before request
// eventually calling `next()`
});
app.use(app.router);
An example of this is the logger middleware, which will append to the log after the response by default.
Just make sure this "middleware" is used before app.router as order does matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With