【问题标题】:Express - Setting different maxAge for certain filesExpress - 为某些文件设置不同的 maxAge
【发布时间】:2013-07-01 23:43:27
【问题描述】:

我正在构建一个单页应用程序,使用 Express 作为后端,使用 AngularJS 作为前端,但遇到了一些缓存问题。

我没有使用 express 视图,只使用 express.static 中间件提供文件。

我的静态文件位于public/apppublic/dist 中,具体取决于环境(dist 有缩小文件)。

app.use app.router
app.use express.static(cwd + '/public/' + publicFolder, maxAge: MAX_AGE)

当请求“/”时,app.router 会验证用户是否已登录,如果一切正常,则通过express.static 提供index.html(我只是在控制器中调用next())。如果用户没有登录,它会被重定向到login.html

我的问题是,如果我设置 maxAge,我的 index.html 文件会被缓存,并且对“/”的第一个请求不会通过 router。即使我没有登录,我也可以进入应用程序。

如果我将 maxAge 设置为 0,问题就会消失,但我想缓存我所有的 *.js 和 *.css 文件。

解决此类问题的正确方法是什么?开始使用视图?不同的express.static 挂载点?

【问题讨论】:

  • 非常重要的问题需要更大声的声音。可以想象有多少人在这个话题上头破血流。谢谢你的解释。

标签: node.js express


【解决方案1】:

您始终可以定义单独的路由,而不必使用视图(尽管视图模板不是一个坏主意)。通过这种方式,您可以定义 index.html 只是为了应用特殊情况 maxAge

请务必将路由放在静态中间件之前。

如果您愿意,您甚至可以使用send,这是static 中间件在幕后使用的同一个静态服务器。比如:

// install send from npm
var send = require("send");

app.get("/index.html", function (req, res) {
  send(req, "/index.html")
    .maxage(0)
    .root(__dirname + "/public")
    .pipe(res);
});

或者更底层的流方式,比如:

app.get("/index.html", function (req, res) {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Cache-Control', 'public, max-age=0');

  // Note that you'd probably want to stat the file for `content-length`
  // as well.  This is just an example.

  var stream = fs.createReadStream(__dirname + '/public/index.html');
  stream.pipe(res);
});

【讨论】:

    猜你喜欢
    • 2015-09-16
    • 1970-01-01
    • 2015-11-02
    • 2012-03-31
    • 1970-01-01
    • 2020-06-09
    • 2013-03-08
    • 1970-01-01
    • 2014-05-20
    相关资源
    最近更新 更多