Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Connect or Express middleware to modify the response.body

Connect or Express middleware to modify the response.body

Problem

I would like to have a middleware function which modifies the response body.

This is for an express server.

Something like:

function modify(req, res, next){
  res.on('send', function(){
    res.body = res.body + "modified"
  });

  next();
}

express.use(modify);

I don't understand what event to listen for. Any help or documentation would be appreciate.

Problem courtesy of: The Who

Solution

You don't need to listen to any events. Just make it

function modify(req, res, next){
  res.body = res.body + "modified";

  next();
}

And use it after you use the router. This way after all your routes have executed you can modify the body

Solution courtesy of: Christopher Tarquini

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Connect or Express middleware to modify the response.body

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×