如何使用Express/Nodejs缓存单个资源

n0p*_*0pe 3 caching http-headers node.js express

我服务的背景图片相当大,我想让它永久缓存.我想我应该发送一个最大年龄为无穷大的缓存头.我怎样才能以干净和正确的方式做到这一点.我正在使用express(开箱即用)并且没有任何缓存模块.

Dan*_*iel 5

您可以设置一个中间件处理程序,它可以匹配静态背景图像的路径,然后设置一个缓存控制头.这将为您的图像设置缓存控制标头,但不为其他静态资源设置.

app.configure(function(){
  app.use(function(req, res, next) {
    var matchUrl = '/background.jpg';
    if(req.url.substring(0, matchUrl.length) === matchUrl) {
      res.setHeader("Cache-Control", "max-age=31556926");
    }
    return next();
  });
  app.use(express.static(path.join(application_root, "StaticPages")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
Run Code Online (Sandbox Code Playgroud)

订单很重要.您的中间件功能需要在express.static处理程序之前排成一行.