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

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

问题描述

ExpressJS 中间件 reqresnext 有像 .on.pipe<这样的钩子/代码>.

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

但我正在寻找 app.getapp.post 方法的钩子.

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

推荐答案

app.use() 和中间件可用于before"和'close''finish' 事件可用于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);

一个例子是 logger 中间件,默认情况下,它将在响应后附加到日志中.

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.

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

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