之前和之后挂钩请求快递(在任何req之前执行,并在任何res之后执行) [英] before and after hooks for a request in express (to be executed before any req and after any res)

查看:94
本文介绍了之前和之后挂钩请求快递(在任何req之前执行,并在任何res之后执行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ExpressJS中间件 req res next have钩子像 .on .pipe

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

但是我正在寻找 app.get app.post 方法的钩子。

But I'm looking for hooks for the app.get and app.post methods.

推荐答案

app.use()和中间件可以用于 之前的 'close' c> / p>

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.

请确保在 app.router 之前使用这个中间件,因为订单很重要。

Just make sure this "middleware" is used before app.router as order does matter.

这篇关于之前和之后挂钩请求快递(在任何req之前执行,并在任何res之后执行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆