如何设置非静态文件响应的最大年龄

如何在expressjs中为非静态文件响应设置max-age参数。

我的代码:

app.get('/hello', function(req, res) { res.set('Content-Type', 'text/plain'); res.set({'maxAge':5}); res.send("Hello Message from port: " + port); res.status(200).end() }) 

我试过这个:

  res.set({'max-age':5}); 

另外这个:

  res.set({'Cache-Control':'max-age=5'}); 

它与res.SendFile(file,{maxAge: 5})工作正常但是静态文件的问题是我看到只有在服务器启动后的第一个http响应头中反映的'max-age'。

即使文件是新鲜的(状态200),所有随后的响应标题都显示'max-age = 0'

您不能设置标题:

 res.set({'maxAge':5}); 

要么:

 res.set({'max-age':5}); 

因为不是设置Cache-Control头,而是分别设置maxAgemax-age头,它们不是有效的HTTP头。

您可以使用以下设置:

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

要么:

 res.set({'Cache-Control': 'max-age=5'}); 

看到:

 app.get('/hello', function(req, res) { res.set('Content-Type', 'text/plain'); res.set('Cache-Control', 'max-age=5'); res.send("Hello Message from port: " + port); res.status(200).end() }); 

您可以使用curl来查看标题:

 curl -v http://localhost:3333/hello 

(只需使用你的端口而不是3333)

如果它没有在每个响应中包含你的Cache-Control头部,那么可能是一些中间件搞乱了你的头文件,或者你有一个代理服务器来改变它们。

另外请记住,您正在使用5秒的max-age ,因此caching非常短。

看到: