Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js- add response body

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();
    });
like image 857
yuria Avatar asked Sep 21 '16 08:09

yuria


Video Answer


2 Answers

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
like image 119
robertklep Avatar answered Oct 17 '22 08:10

robertklep


You have to use res.json(body). It will send "body" as a response body.Make sure body should be object.

like image 6
Vaibhav Patil Avatar answered Oct 17 '22 09:10

Vaibhav Patil