Hook How to execute code before any req and after any res

suggest change

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);

        // actions after response
    }
    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    // action before request
    // eventually calling `next()`
    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.


Original post is here

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Web apps with Express:
* Hook How to execute code before any req and after any res

Table Of Contents
1 npm
2 Web apps with Express
41 cli
43 grunt
59 Hack
64 ES6
67 Redis
69 MongoDB
86 MongoDB
87 Lodash
91 CORS
105 N-API
108 Require