1

Is it possible in a middleware to get the data just sent by my API ?

For exemple I have a nodejs Server with this middleware:

    var middleware = function(req, res, next) {
       res.on('finish', function() {
          console.log(res.statusCode); // display 200
          console.log(res.body); // display empty data
      });
      next();
   };

And my API:

    app.get('/url', function(req, res) {
       res.status(200).json({name:'john'}).end();
    });

But in my middleware, I only can get the statusCode '200', but not the object {name:'john'}.

Anyone can help me ?

Thanks.

Sparw
  • 2,688
  • 1
  • 15
  • 34

1 Answers1

2

Add the app.use(middleware); after the router.

Source : Connect or Express middleware to modify the response.body

EDIT : Sorry, the answer I link works for old versions of Express. I have read the Express source code, and body is never saved in res when res.json() or res.send() are called.

To edit the body in Express 4, you seem to need to override res methods, or use a package which do it, like express-mung (https://www.npmjs.com/package/express-mung).

Community
  • 1
  • 1
F. Kauder
  • 879
  • 5
  • 9