用快递发送回应后可以使用某种“中间件”吗?

express中的典型中间件在请求到达路由之前使用,例如首先进行authentication,然后执行特定路由的代码,然后发送响应。

我想知道路由命中之后是否有可能有中间件这样的东西。

假设我有五条路线都回应了一些JSON,并且我想logging发送的JSON,每当一条路线被击中时。
每当我在路由中发送响应时,我都可以手动进行日志logging,如下所示:

console.log(data); res.json(data); 

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

 /* 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); } 

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

附加一个在路由后执行的中间件是不太可能的,但是你可以执行一个中间件,

 app.use(function(req, res, next){ res.on('finish', function(){ // Do whatever you want this will execute when response is finished }); next(); }); 

https://stackoverflow.com/a/21858212/3556874