使用 express 发送响应后是否可以使用某种“中间件”?

Lau*_*ura 3 node.js express

express 中典型的中间件是在请求命中路由之前使用的,例如首先进行身份验证,然后执行特定路由的代码,然后发送响应。

我想知道路由被命中是否有可能有一个像中间件这样的东西。

假设我有五个路由,它们都以一些 json 响应,我想在每次命中其中一个路由时记录发送的 json。
每次在路由中发送响应时,我都可以手动登录,如下所示:

console.log(data);
res.json(data);
Run Code Online (Sandbox Code Playgroud)

但这对我来说似乎是多余的。更好的方法可能是将其包装在一个函数中以在路由中调用,但这需要每次都传递响应对象,如下所示:

/* instead of the above */
send(data, res);

/* and then somewhere else usable for all routes */
function send(data, res) {
    console.log(data);
    res.json(data);
}
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎也有点不好,所以我想知道这是否是首选方式,或者是否有办法使用某种“中间件”,这将允许以通常的方式发送响应并挂钩在那之后。

Nae*_*ikh 6

附加一个在路由之后执行的中间件是不可能的,但是你可以执行一个中间件,它在响应时绑定一个完成事件,

app.use(function(req, res, next){
  res.on('finish', function(){

    // Do whatever you want this will execute when response is finished
  });
  next();
});
Run Code Online (Sandbox Code Playgroud)

还有/sf/answers/1530074871/