如何在 express.js 中针对 JSON 响应设置 cache-control 策略?
我的 JSON 响应根本没有改变,所以我想积极地缓存它。
我找到了如何对静态文件进行缓存,但找不到如何对动态数据进行缓存。
最佳答案
不优雅的方法是在任何 JSON 输出之前简单地添加对 res.set()
的调用。在那里,你可以指定设置缓存控制头,它会相应地缓存。
res.set('Cache-Control', 'public, max-age=31557600'); // one year
另一种方法是简单地将 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);
})
编辑:从 res.setHeader
更改为 res.set
for Express v4
关于node.js - 动态数据 Express.JS 的缓存控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462717/