Express + request. Change of headings in the middle of a stream

I use express as my server and request to receive content from a window with a stream.

I have this very simple function for streaming data from a stream up to a client:

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

The upstream field returns the Cache-Control: no-cache header, which I would like to change, so that Nginx (reverse proxy) can cache the response.

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

I 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 causes an Error: Can't set headers after they are sent .

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

+8
caching header express request
source share
2 answers

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); } } 
+6
source share

It seems that the request has been updated since sending the accepted answer, which simplified this process. Now you can 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!

+8
source share

All Articles