javascript express.js - 如何拦截 response.send() / response.json()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33732509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:50:37  来源:igfitidea点击:

express.js - how to intercept response.send() / response.json()

javascriptexpress

提问by pleerock

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 .sendmethods and make some changes to someData. Is there any way in express.js? (hooks, listeners, interceptors, ...)?

假设我有多个地方可以调用response.send(someData). 现在我想创建一个全局拦截器,我可以在其中捕获所有.send方法并对someData. express.js 有什么办法吗?(钩子,侦听器,拦截器,...)?

回答by Sami

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);

回答by Don

Yes this is possible. There are two ways to do this, one is to use a library that provides the interception, with the ability to run it based on a specific condition: https://www.npmjs.com/package/express-interceptor

是的,这是可能的。有两种方法可以做到这一点,一种是使用提供拦截的库,并能够根据特定条件运行它:https: //www.npmjs.com/package/express-interceptor

The other option is to just create your own middleware (for express) as follows:

另一种选择是创建您自己的中间件(用于 express),如下所示:

function modify(req, res, next){
  res.body = "this is the modified/new response";

  next();
}
express.use(modify);

回答by cpri

for those finding on google, based off the top answer:

对于那些在谷歌上找到的人,基于最佳答案:

app.use((req, res, next) => {
    let oldSend = res.send
    res.send = function(data) {
        console.log(data) // do something with the data
        res.send = oldSend // set function back to avoid the 'double-send'
        return res.send(data) // just call as normal with data
    }
    next()
})