我需要修改模块发送给客户端的响应数据,因为模块使用res.send我似乎无法找到一种方法让我在将数据传送到客户端之前对其进行修改.
是否有任何类型的中间件/事件可用于res.send在执行之前捕获和修改数据?
我知道router.use存在但它在router.post函数之前调用,而不是在res.send发送到客户端之前调用.所以我需要某种中间件,它在router.post函数完成之后但在将任何内容发送到客户端之前调用.
Far*_*hat 14
那么你可以覆盖发送功能:
app.use(function (req, res) {
var send = res.send;
res.send = function (body) { // It might be a little tricky here, because send supports a variety of arguments, and you have to make sure you support all of them!
// Do something with the body...
send.call(this, body);
};
});
Run Code Online (Sandbox Code Playgroud)
如果你想支持的不仅仅是调用send(比如调用end方法),那么你必须覆盖更多的函数......
你可以检查connect-livereload如何将脚本添加到任何html输出.
这里还有一个解决方案:
Run Code Online (Sandbox Code Playgroud)expressApp.use(function (req, res, next) { req.on("end", function () { console.log('on request end'); }); next(); });
重要提示:要工作,需要将其放置在主体解析器之前,因为它会重新创建响应对象。看到这个答案