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

后端 未结 4 2161
我寻月下人不归
我寻月下人不归 2020-12-08 14:57

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 meth

相关标签:
4条回答
  • 2020-12-08 15:15

    You can simply do it using NODEJS and Express, say you are calling an API and want to send modify the data before sending response back.

    router.get('/id', (req,res) => {
    ... //your code here filling DATA
    
      let testData = {
        "C1": "Data1",
        "C2": "Data2",
        "yourdata": DATA
      };          
      res.send(testData);
    });
    
    0 讨论(0)
  • 2020-12-08 15:19

    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);
    
    0 讨论(0)
  • 2020-12-08 15:24

    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()
    })
    
    0 讨论(0)
  • 2020-12-08 15:33

    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

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

    function modify(req, res, next){
      res.body = "this is the modified/new response";
    
      next();
    }
    express.use(modify);
    
    0 讨论(0)
提交回复
热议问题