【问题标题】:Cache Control for Dynamic Data Express.JS动态数据 Express.JS 的缓存控制
【发布时间】:2014-10-17 05:37:45
【问题描述】:

如何在 express.js 中针对 JSON 响应设置 cache-control 策略?

我的 JSON 响应根本没有改变,所以我想积极地缓存它。

我找到了如何对静态文件进行缓存,但找不到如何对动态数据进行缓存。

【问题讨论】:

    标签: node.js caching express


    【解决方案1】:

    不优雅的方法是在任何 JSON 输出之前简单地添加对 res.set() 的调用。在那里,您可以指定设置缓存控制头,它会相应地缓存。

    res.set('Cache-Control', 'public, max-age=31557600'); // one year
    

    另一种方法是在路由中为您的 JSON 响应简单地设置一个 res 属性,然后使用备用中间件(在错误处理之前)呈现和发送 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

    【讨论】:

    【解决方案2】:

    你可以这样做,例如:

    res.set('Cache-Control', 'public, max-age=31557600, s-maxage=31557600'); // 1 year
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 2017-02-18
    • 2017-10-19
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2012-06-06
    • 2016-05-25
    • 2019-06-09
    相关资源
    最近更新 更多