Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mikeal's NodeJS Request modify body before piping

I'm using mikeal's awesome request module for NodeJS. I'm also using it with express where I'm proxying a call to the API for getting around CORS issues 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 I can modify the body before I pipe the request's response back to express?

like image 669
Ahmed Nuaman Avatar asked Aug 09 '13 06:08

Ahmed Nuaman


2 Answers

Based on this answer: Change response body before outputting in node.js I made a working example that I use on my own app:

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 will be welcome, hope it helps!

like image 157
JAM Avatar answered Oct 10 '22 18:10

JAM


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

like image 2
Pickels Avatar answered Oct 10 '22 16:10

Pickels