express.js - 如何拦截response.send()/ response.json() [英] express.js - how to intercept response.send() / response.json()
本文介绍了express.js - 如何拦截response.send()/ response.json()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
response.send(someData)
。现在我想创建一个单一的全局拦截器,其中我捕获所有 .send
方法,并对 someData
进行一些更改。 express.js有什么办法吗? (钩子,听众,拦截器,...)?解决方案
你可以定义一个中间件如下(从这里采取和修改 answer )
function modifyResponseBody(req,res,next){
var oldSend = res.send;
res.send = function(data){
// arguments [0](或`data`)包含响应体
arguments [0] =modified: +参数[0];
oldSend.apply(res,arguments);
}
next();
}
app.use(modifyResponseBody);
Lets say I have multiple places where I call response.send(someData)
. Now I want to create a single global interceptor where I catch all .send
methods and make some changes to someData
. Is there any way in express.js? (hooks, listeners, interceptors, ...)?
解决方案
You can define a middleware as below (taken and modified from this answer)
function modifyResponseBody(req, res, next) {
var oldSend = res.send;
res.send = function(data){
// arguments[0] (or `data`) contains the response body
arguments[0] = "modified : " + arguments[0];
oldSend.apply(res, arguments);
}
next();
}
app.use(modifyResponseBody);
这篇关于express.js - 如何拦截response.send()/ response.json()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文