Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 640
chebad Avatar asked Dec 03 '22 10:12

chebad


1 Answers

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.

like image 193
shaochuancs Avatar answered Feb 09 '23 01:02

shaochuancs