Reputation: 553
I would like to add a body
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 res.send
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);
};
next();
});
Upvotes: 15
Views: 44831
Reputation: 2983
You have to use res.json(body)
. It will send body
as a response body. Make sure body should be object.
Upvotes: 6
Reputation: 203286
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:
res.send
with the object as argumentres.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 argumentUpvotes: 18