Cache Control for Dynamic Data Express.JS

2019-01-13 21:16发布

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.

2条回答
Anthone
2楼-- · 2019-01-13 21:46

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-13 21:54

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

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);
})

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

查看更多
登录 后发表回答