如何在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()
})
Run Code Online (Sandbox Code Playgroud)
我试过这个:
res.set({'max-age':5});
Run Code Online (Sandbox Code Playgroud)
还有这个:
res.set({'Cache-Control':'max-age=5'});
Run Code Online (Sandbox Code Playgroud)
它工作正常res.SendFile(file,{maxAge: 5})
,但静态文件的问题是我看到“max-age”仅在服务器启动后的第一个http响应上反映在标头中。
所有后续响应标头均显示“max-age = 0”,即使文件是新鲜提供的(状态 200)
您不能使用以下方式设置标题:
res.set({'maxAge':5});
Run Code Online (Sandbox Code Playgroud)
或者:
res.set({'max-age':5});
Run Code Online (Sandbox Code Playgroud)
因为Cache-Control它不会设置标头,而是分别设置maxAge或max-age标头,它们不是有效的 HTTP 标头。
您可以通过以下方式设置:
res.set('Cache-Control', 'max-age=5');
Run Code Online (Sandbox Code Playgroud)
或者:
res.set({'Cache-Control': 'max-age=5'});
Run Code Online (Sandbox Code Playgroud)
看:
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()
});
Run Code Online (Sandbox Code Playgroud)
您可以使用curl来查看标题:
curl -v http://localhost:3333/hello
Run Code Online (Sandbox Code Playgroud)
(只需使用您的端口而不是 3333)
如果它没有Cache-Control在每个响应中包含您的标头,那么可能某些中间件弄乱了您的标头,或者您可能有一个代理服务器来更改它们。
另请记住,您使用的max-age是 5 秒,因此缓存非常短。
看: