0

The thing I want to do is modify the response body.

For this I am using a middleware that gets called at every request. To achieve it, I took a demo application from github https://github.com/ccoenraets/nodecellar . I added a middleware in the server.js similar to the example given on express logging response body.

Still I am unable to modify the response body, as res.send = function (string) does not get called.

Below mentioned is the code. Please let me know what wrong am I doing here.

 var express = require('express'),
path = require('path'),
http = require('http'),
wine = require('./routes/wines');

var app = express();
app.configure(function () {
    app.set('port', process.env.PORT || 4000);
    app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser()), 
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(logResponseBody);
});

app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);
http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
    });
 function logResponseBody(req,res,next){
 var send = res.send; 
 console.log("send resp is: "+send);
 res.send = function (string) {
 var body = string instanceof Buffer ? string.toString() : string;
   console.log("Body found is: "+body);
   body = body.replace(/<\/head>/, function (w) {
   return 'Modified head' + w;
  });
 send.call(this, body);
 }; 
 res.on('finish', function(){
console.log("Finished " + res.headersSent); // for example
console.log("Finished " + res.statusCode);  // for example
})
next();
} 

PS: I am starting a new thread for a similar question as I have less than 50 reputation.Therefore cant add comments there.

Aditya
  • 79
  • 1
  • 8

1 Answers1

0

The best way to add middleware to an express app is to use the app.use method, so you can remove the whole http.createServer block and replace it for something like

app.use(function(req, res, next) {
  //do everything you want to happen on every request
  next();
});

app.listen(app.get('port'), function() {
  console.log('listening on port ' + app.get('port'));
});

For more info on app.use, check the express app use documentation.

ruedamanuel
  • 1,930
  • 1
  • 22
  • 23
  • I have tried it using app.listen instead of http.listen but still its not working. – Aditya Aug 05 '16 at 04:46
  • the important part here is to take out the contents of the callback in the listen method and put it in the app.use method – ruedamanuel Aug 05 '16 at 16:52