【发布时间】:2014-10-17 05:37:45
【问题描述】:
如何在 express.js 中针对 JSON 响应设置 cache-control 策略?
我的 JSON 响应根本没有改变,所以我想积极地缓存它。
我找到了如何对静态文件进行缓存,但找不到如何对动态数据进行缓存。
【问题讨论】:
如何在 express.js 中针对 JSON 响应设置 cache-control 策略?
我的 JSON 响应根本没有改变,所以我想积极地缓存它。
我找到了如何对静态文件进行缓存,但找不到如何对动态数据进行缓存。
【问题讨论】:
不优雅的方法是在任何 JSON 输出之前简单地添加对 res.set() 的调用。在那里,您可以指定设置缓存控制头,它会相应地缓存。
res.set('Cache-Control', 'public, max-age=31557600'); // one year
另一种方法是在路由中为您的 JSON 响应简单地设置一个 res 属性,然后使用备用中间件(在错误处理之前)呈现和发送 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);
})
编辑:Express v4 从res.setHeader 更改为res.set
【讨论】:
res.header('Cache-Control', 'public, max-age=31557600') 吗?
res.set({ headers }) 或 res.header({ headers }) 而不是 res.setHeader({ headers }) 作为 it is now documented。
public 有什么作用?
你可以这样做,例如:
res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year
【讨论】: