yuria yuria - 1 month ago 6
Node.js Question

Express.js- add response body

I would like to add a

property to Express.js' response object, which will be called every time the
send method is called
I do it by adding the following code as a middleware,

but for some reason, when I call
this function is called twice (once when body is object and in the 2nd time the same object butas a string )
1.why is it being called twice?
2.why and when is it being converted to string?

applicationsRouter.use(function (req, res, next) {
var send = res.send;
res.send = function (body) {
res.body = body
send.call(this, body);


You are probably using something like this:

res.send({ foo : 'bar' });

In other words, you're passing an object to res.send.

This will do the following:

  • call res.send with the object as argument
  • res.send checks the argument type and sees that it's an object, which it passed to res.json
  • res.json converts the object to a JSON string, and calls res.send again, but this time with the JSON string as argument