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

Say*_*ald 29 caching node.js express

如何在json响应中的express.js中设置cach-controll策略?我的json响应完全没有改变,所以我想积极地缓存它.我发现如何对静态文件进行缓存,但无法找到如何在动态数据上进行缓存.

Jas*_*son 45

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

res.set('Cache-Control', 'public, max-age=31557600'); // one year
Run Code Online (Sandbox Code Playgroud)

另一种方法是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);
})
Run Code Online (Sandbox Code Playgroud)

编辑:从改变res.setHeaderres.set的快递V4

  • 小心,在Express 4.x中,你必须使用`res.set({headers})`或`res.header({headers})`而不是`res.setHeader({headers})`作为[它是现已记录](http://expressjs.com/api.html#res.set). (10认同)

小智 7

你可以这样做,例如:

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

  • 虽然此代码片段可以解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您建议代码的原因。 (16认同)