node.js - 动态数据 Express.JS 的缓存控制

标签 node.js caching express

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

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

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

最佳答案

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

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

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

编辑:从 res.setHeader 更改为 res.set for Express v4

关于node.js - 动态数据 Express.JS 的缓存控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462717/

相关文章:

node.js - mongodb : find() query in a collection

mysql - 使用多个服务器处理过时的缓存

iphone - 如何缓存表格 View 的某些内容?

javascript -/page1/和/page2/显示相同 - Express

node.js - Jade 在输出中添加撇号

javascript - Firebase 函数总是超时完成

javascript - 使用node.js将rails应用程序部署到ubuntu

c - 优化贝塞尔滤波器的实现

javascript - 在 Node.JS/express 全局访问 Firebase

javascript - 尝试使用 Express 将数据插入 MySql 数据库时出错