问题:使用 Express,如何仅更改特定子文件夹或文件类型(即仅限图像)中的文件的 maxAge header
我尝试了以下方法,但没有成功:
// Setting the app router and static folder
var fiveDays = 432000000;
// Use maxAge 0 for everything
var app = express();
app.use(express.static(path.resolve('./public'), { maxAge: 0 }));
// only cache images for 5 days
app.use(express.static(path.resolve('./public/modules/core/img'), { maxAge: fiveDays }));
app.use(express.static(path.resolve('./public/modules/filters/img'), { maxAge: fiveDays }));
app.use(express.static(path.resolve('./public/modules/spotlights/img'), { maxAge: fiveDays }));
app.use(express.static(path.resolve('./public/modules/users/img'), { maxAge: fiveDays }));
结果:
所有资源返回时 maxAge = 0。
预期:
图像的 maxAge header 为 432000000。
我知道它可能在两个单独的文件夹上调用,我的问题是我想要更改标题的图像位于我的主要 express.static 调用的子文件夹内。
最佳答案
最终使用了serve-static模块来根据mime类型完成此任务:
var serveStatic = require('serve-static');
app.use(serveStatic(path.resolve('./public'), {
maxAge: '5d',
setHeaders: setCustomCacheControl
}));
function setCustomCacheControl(res, path) {
if (serveStatic.mime.lookup(path) === 'text/html') {
// Custom Cache-Control for HTML files
res.setHeader('Cache-Control', 'public, max-age=0')
}
}
关于javascript - 使用 Express 更改文件夹或文件类型中的文件的 http header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34076372/