javascript - 使用 Express 更改文件夹或文件类型中的文件的 http header ?

标签 javascript node.js express

问题:使用 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/

相关文章:

node.js - 如何使用 Express 和 PassportJS 正确报告无效登录?

node.js - 未找到授权 token - Express-JWT 和 Auth0

javascript - 平滑滚动像素步骤

javascript - 如何检测不触发 onpopstate 的 pushState/replaceState

javascript - 使用CoreOS和多个Docker容器构建应用程序的正确方法

node.js - Yeoman 的 angular-fullstack 有 jpegtran-bin 错误并且 3 次失败

javascript - 我需要在 Express 中附加这些嵌套函数的列表,但这些项目不会存储

javascript - D3 选择具有特定类别或类别组合的所有元素

javascript - Highcharts 不会在我的 MVC4 .NET 项目中呈现

node.js - 建模 : npm install error