Gabriele B
Gabriele B

Reputation: 2685

Change response body before outputting in node.js

I'm new to Node.js. I'm tryinbg to build a small server acting as proxy for a POST call to a opendata service, then doing some stuff, binding to a presentation layer, finally outputting to browser.

Here's the code:

dispatcher.onGet("/metro", function(req, res) {
  var r = request({body: '<?xml version="1.0" encoding="ISO-8859-1" ?><poirequest><poi_id>87087</poi_id><lng>0</lng></poirequest>'}, function (error, response, body) { 
if (!error && response.statusCode == 200) {
   console.log('Public transformation public API called');
  }
}).pipe(res);

res.on('finish', function() {
  console.log('Request completed;');
});

}); 

http.createServer(function (req, res) {
  dispatcher.dispatch(req, res);
}).listen(1337, '0.0.0.0');
console.log('Server is listening');

The dispatcher is the simplest i found on mpm: https://npmjs.org/package/httpdispatcher The question is: how can I alter (basically, html-code stripping) the response body before outputting to the output pipe?

Upvotes: 3

Views: 5135

Answers (1)

Timothy Strimple
Timothy Strimple

Reputation: 23060

You can use something like concat-stream to accumulate all of the stream data and then pass it on to a callback where you can manipulate it before returning it to the browser.

var concat = require('concat-stream');

dispatcher.onGet("/metro", function(req, res) {
  write = concat(function(completeResponse) {
    // here is where you can modify the resulting response before passing it back to the client.
    var finalResponse = modifyResponse(completeResponse);
    res.end(finalResponse);
  });

  request('http://someservice').pipe(write);
}); 

http.createServer(dispatcher.dispatch).listen(1337, '0.0.0.0');
console.log('Server is listening');

Upvotes: 4

Related Questions