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

南笙酒味 提交于 2020-01-09 07:15:49

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20175806/before-and-after-hooks-for-a-request-in-express-to-be-executed-before-any-req-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!