GJK
GJK

Reputation: 37369

Edit response headers before piping

I have a small proxy for certain requests in Express. Using the request library, I have fairly concise code:

app.use('/api', function(req, res) {
    var url = rewriteUrl(req.url);

    var newReq = request(url, function(error) {
        if (error) {
            logError(error);
        }
    });

    req.pipe(newReq).pipe(res);
});

My problem is that the response from the API server contains a bunch of unwanted headers that I want to remove. How can I remove the headers from the response of newReq before piping it to res?

Upvotes: 38

Views: 19738

Answers (4)

Yoshiki Shibukawa
Yoshiki Shibukawa

Reputation: 5089

It is easy with request.

request("https://example.com/image.png")
.on("response", remoteRes => {
    // You can add/remove/modify headers here
    remoteRes.headers["content-disposition"] = "attachment; filename=awesome.png";
})
.pipe(res);

Upvotes: 13

barbatus
barbatus

Reputation: 244

There is more elegant way to modify/remove headers by setting a pipe filter as follows:

const req = request.get(url);
req.pipefilter = function(response, dest) {
  // remove headers
  for(const h in response.headers) {
    dest.removeHeader(h);
  }
  // or modify
  dest.setHeader('Content-Type', 'text/html')
}
req.pipe(resp)

Upvotes: 3

GJK
GJK

Reputation: 37369

mscdex's answer did work for me, but I found a way that I think is slightly cleaner. In my original code, I had this line:

req.pipe(newReq).pipe(res);

I replaced that with these lines:

req.pipe(newReq).on('response', function(res) {
    delete res.headers['user-agent'];
    // ...
}).pipe(res);

Upvotes: 71

mscdex
mscdex

Reputation: 106698

With the request module, there currently isn't a way (AFAIK) to have a callback and not buffer the server response. So here is how you might do it with the built-in http.request:

app.use('/api', function(req, res) {
  var url = rewriteUrl(req.url);

  var newReq = http.request(url, function(newRes) {
    var headers = newRes.headers;

    // modify `headers` here ...

    res.writeHead(newRes.statusCode, headers);
    newRes.pipe(res);
  }).on('error', function(err) {
    res.statusCode = 500;
    res.end();
  });

  req.pipe(newReq);
});

Upvotes: 18

Related Questions