Mikeal NodeJS Request for body change before piping

I am using mikeal's awesome request module for NodeJS. I also use it with express , where I proxy an API call to solve CORS problems for older browsers:

app.use(function(request, response, next) { var matches = request.url.match(/^\/API_ENDPOINT\/(.*)/), method = request.method.toLowerCase(), url; if (matches) { url = 'http://myapi.com' + matches[0]; return request.pipe(req[method](url)).pipe(response); } else { next(); } }); 

Is there a way to change the body before I answer the request response to express ?

+6
source share
2 answers

Based on this answer: Change the body of the response before release in node.js I made a working example that I use in my own application:

 app.get("/example", function (req, resp) { var write = concat(function(response) { // Here you can modify the body // As an example I am replacing . with spaces if (response != undefined) { response = response.toString().replace(/\./g, " "); } resp.end(response); }); request.get(requestUrl) .on('response', function (response) { //Here you can modify the headers resp.writeHead(response.statusCode, response.headers); } ).pipe(write); }); 

Any improvements would be welcome, hope this helps!

+9
source

You probably want to use transform stream . After some googling, I found the following blog post .

+1
source

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


All Articles