如何在express.js中为JSON响应设置缓存控制策略?
由于我的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);
})
编辑:针对Express v4,已从res.setHeader
更改为res.set
res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year
最近我也有同样的问题,对我有用的方法是:
const express = require('express');
const app = express();
const port = 3000;
let options = {
maxAge: '2y',
etag: false
}
app.use(express.static('public', options));
通过maxAge
,您可以设置缓存时间。
文档:https://expressjs.com/zh-cn/starter/static-files.html
res.header('Cache-Control', 'public, max-age=31557600')
吗? - Yuri Astrakhanres.set({ headers })
或res.header({ headers })
替代res.setHeader({ headers })
,因为官方文档已经更新。 - Clément Fioriopublic
是做什么用的? - João Pimentel Ferreira