node.js 动态数据 Express.JS 的缓存控制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25462717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cache Control for Dynamic Data Express.JS
提问by Sayat Satybald
How it is possible to set up a cache-controlpolicy in express.json JSON response?
如何在 JSON 响应的express.js 中设置缓存控制策略?
My JSON response doesn't change at all, so I want to cache it aggressively.
我的 JSON 响应根本没有改变,所以我想积极地缓存它。
I found how to do caching on static files but can't find how to make it on dynamic data.
我找到了如何对静态文件进行缓存,但找不到如何对动态数据进行缓存。
回答by Jason
The inelegant way is to simply add a call to res.set()prior to any JSON output. There, you can specify to set the cache control header and it will cache accordingly.
不优雅的方法是res.set()在任何 JSON 输出之前简单地添加一个调用。在那里,您可以指定设置缓存控制标头,它会相应地缓存。
res.set('Cache-Control', 'public, max-age=31557600'); // one year
Another approach is to simply set a resproperty to your JSON response in a route then use fallback middleware (prior to the error handling) to render and send the JSON.
另一种方法是简单地res为路由中的 JSON 响应设置一个属性,然后使用回退中间件(在错误处理之前)来呈现和发送 JSON。
app.get('/something.json', function (req, res, next) {
res.JSONResponse = { 'hello': 'world' };
next(); // important!
});
// ...
// Before your error handling middleware:
app.use(function (req, res, next) {
if (! ('JSONResponse' in res) ) {
return next();
}
res.set('Cache-Control', 'public, max-age=31557600');
res.json(res.JSONResponse);
})
Edit: Changed from res.setHeaderto res.setfor Express v4
编辑:从改变res.setHeader到res.set的快递V4
回答by B?ng Nguy?n H?u
You can do it like this, for example :
你可以这样做,例如:
res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year

