Say*_*ald 29 caching node.js express
如何在json响应中的express.js中设置cach-controll策略?我的json响应完全没有改变,所以我想积极地缓存它.我发现如何对静态文件进行缓存,但无法找到如何在动态数据上进行缓存.
Jas*_*son 45
不优雅的方法是res.set()在任何JSON输出之前简单地添加一个调用.在那里,您可以指定设置缓存控制标头,它将相应地缓存.
res.set('Cache-Control', 'public, max-age=31557600'); // one year
Run Code Online (Sandbox Code Playgroud)
另一种方法是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);
})
Run Code Online (Sandbox Code Playgroud)
编辑:从改变res.setHeader到res.set的快递V4
小智 7
你可以这样做,例如:
res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42540 次 |
| 最近记录: |