before and after hooks for a request in express (to be executed before any req and after any res)

前端 未结 1 345
感情败类
感情败类 2020-12-05 14:24

ExpressJS middleware req, res, next have hooks like .on and .pipe.

But I\'m looking for hooks for th

相关标签:
1条回答
  • 2020-12-05 14:56

    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.

    0 讨论(0)
提交回复
热议问题