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

suggest change

app.use() runs code before later routes. The response close and finish events run code after the response is done. Register this middleware before the routes. Express 4 has no app.router; middleware runs in the order it was added.

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

The morgan logger does the same kind of "after" work: it writes the log line when the response finishes.

Register this middleware before routes that should be wrapped. Order matters.


Original post is here

Feedback about page:

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



Table Of Contents