Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  137] [ 4]  / answers: 1 / hits: 31769  / 9 Years ago, mon, november 16, 2015, 12:00:00

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, ...)?


More From » node.js

 Answers
192

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

[#64388] Thursday, November 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rayvenc

Total Points: 666
Total Questions: 125
Total Answers: 99

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
;