alexcline
alexcline

Reputation: 450

Express + Request Changing headers mid-stream

I'm using express as my server and request to retrieve content from an up-stream box.

I've got this beautifully simple function to stream data from the up-stream to the client:

function(req, res){
  request("http://example.com").pipe(res);
}

The upstream box is returning a cache header Cache-Control: no-cache that I'd like to modify, so that Nginx (reverse proxy) can cache the response.

Where should I put the res.header('Cache-Control', 60);?

I've tried:

function(req, res){
  var retrieve = request("http://example.com");
  retrieve.on('data', function(chunk){
    if(res.get('Cache-Control') != 60)
      res.header('Cache-Control', 60);
  });
  retrieve.pipe(res);
}

But this throws a Error: Can't set headers after they are sent error.

Is there a listener that fires when the headers are sent, but before writeHeader() is called?

Upvotes: 11

Views: 5141

Answers (2)

cbnz
cbnz

Reputation: 674

It seems request has been updated since the accepted answer was submitted, making this process much easier. You can now do the following:

var resource = request('http://example.com');

resource.on('response', function(response) {
    response.headers['Cache-Control'] = 'max-age=60, public';
});

resource.pipe(res);

Much nicer!

Upvotes: 13

alexcline
alexcline

Reputation: 450

Thanks to Peter Lyons, I was able to get this working using this code:

function(req, res){
  request("http://example.com").pipe(res);

  res.oldWriteHead = res.writeHead;
  res.writeHead = function(statusCode, reasonPhrase, headers){
    res.header('Cache-Control', 'max-age=60, public');
    res.oldWriteHead(statusCode, reasonPhrase, headers);
  }
}

Upvotes: 8

Related Questions