动态数据 Express.JS 的缓存控制 [英] Cache Control for Dynamic Data Express.JS

查看:24
本文介绍了动态数据 Express.JS 的缓存控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 express.js 中针对 JSON 响应设置缓存控制 策略?

How it is possible to set up a cache-control policy in express.js on JSON response?

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

My JSON response doesn't change at all, so I want to cache it aggressively.

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

I found how to do caching on static files but can't find how to make it on dynamic data.

推荐答案

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

The inelegant way is to simply add a call to res.set() prior to any JSON output. There, you can specify to set the cache control header and it will cache accordingly.

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

另一种方法是简单地为路由中的 JSON 响应设置一个 res 属性,然后使用回退中间件(在错误处理之前)来呈现和发送 JSON.

Another approach is to simply set a res property to your JSON response in a route then use fallback middleware (prior to the error handling) to render and send the 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

Changed from res.setHeader to res.set for Express v4

这篇关于动态数据 Express.JS 的缓存控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆