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

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

问题描述

如何在json响应的express.js中设置缓存控制策略?我的json响应根本没有改变,所以我想要积极地缓存它。我发现如何对静态文件进行缓存,但是找不到如何在动态数据中进行缓存。

How it is possible to setup a cach-controll policy in express.js on json response? My json response does'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.setHeader()。在这里,您可以指定设置缓存控制标题,并相应缓存。

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

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

另一种方法是简单地设置一个 res 属性到您的JSON响应中,然后使用回退中间件(在错误处理之前)呈现和发送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.setHeader('Cache-Control', 'public, max-age=31557600');
  res.json(res.JSONResponse);
})

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

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