Modify response body before res.send() executes in ExpressJS

五迷三道 提交于 2021-02-07 04:18:58

问题


In application which I currently develop, it's using Express. In my case I want to get response before it's been sent and modify it (for purpose of JWT). In this application, there is a dozen of endpoints and I don't want to create my own function like sendAndSign() and replace res.send() everywhere in code. I heard there is option to override/modify logic of res.send(...) method.

I found something like this example of modifying, but in my case this doesn't work. Is there any other option (maybe using some plugin) to manage this action?


回答1:


You can intercept response body in Express by temporary override res.send:

function convertData(originalData) {
  // ...
  // return something new
}

function responseInterceptor(req, res, next) {
  var originalSend = res.send;

  res.send = function(){
    arguments[0] = convertData(arguments[0]);
    originalSend.apply(res, arguments);
  };
  next();
}

app.use(responseInterceptor);

I tested in Node.js v10.15.3 and it works well.



来源:https://stackoverflow.com/questions/56648926/modify-response-body-before-res-send-executes-in-expressjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!