Express caching Image stream from Google Cloud Sto

2019-06-07 02:05发布

问题:

I am serving image stream using express 4 with :

app.get('/v1/images/:Uid/', function(req, res) {
    var gcsbucket = gcs.bucket('bucket'),
    remoteReadStream = gcsbucket.file(req.params.Uid+'.jpg').createReadStream();
    remoteReadStream.pipe(res);
});

(the images are stored on Google cloud storage)

I am trying to find a way to tell browsers to cache the images I am serving. I tried to add :

res.set('Cache-Control', 'public, max-age=31557600');

But this is not changing anything when I access the API at http://server/v1/images/1234, it always reload the image.

What is the proper way to tell browsers to cache the response when using stream server-side ?

回答1:

This is actually working :

app.get('/v1/images/:Uid/', function(req, res) {
    var gcsbucket = gcs.bucket('bucket'),
    remoteReadStream = gcsbucket.file(req.params.Uid+'.jpg').createReadStream();
    res.set('Cache-Control', 'public, max-age=31557600');
    remoteReadStream.pipe(res);
});

Strangely, the browser never cache when you access directly the API. However the image is cached when you embed it in an html page like :

<img src="http://server/v1/images/1234">

It is enough for my use case but if someone has the reason why ?