Change the response body to output in node.js

I am new to Node.js. I try to create a small server that acts as a proxy for calling POST for the opendata service, then I do some things, linking to the presentation level, finally outputting to the browser.

Here is 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 easiest one that I found on mpm: https://npmjs.org/package/httpdispatcher The question arises: how can I change (basically, delete the html code) of the response body before going to the output channel?

+3
source share
1 answer

You can use something like concat-stream to accumulate all stream data and then pass it 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'); 
+4
source

Source: https://habr.com/ru/post/951375/


All Articles