Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect or Express middleware to modify the response.body

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.

like image 405
The Who Avatar asked Mar 27 '12 19:03

The Who


People also ask

Can middleware be used in response?

Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects. End the request-response cycle.

What is the purpose of Express middleware?

Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to. In fact, Express itself is compromised wholly of middleware functions.

Can we use middleware in response in node JS?

Typically all middlewares in nodejs/expressjs have access to request, response and next objects. A request is something that's coming from a browser that invokes a particular function to perform certain tasks and return a response. “A particular function” in this case is a middleware.


3 Answers

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

like image 76
Christopher Tarquini Avatar answered Oct 16 '22 17:10

Christopher Tarquini


I believe the OP actually wants to modify the response stream once a middleware has handled the request. Look at the bundled Compress middleware implementation for an example of how this is done. Connect monkey patches the ServerResponse prototype to emit the header event when writeHead is called, but before it is completed.

like image 20
Corey Jewett Avatar answered Oct 16 '22 15:10

Corey Jewett


express-mung is designed for this. Instead of events its just more middleware. Your example would look something like

const mung = require('express-mung')

module.exports = mung.json(body => body.modifiedBy = 'me');
like image 12
Richard Schneider Avatar answered Oct 16 '22 17:10

Richard Schneider