Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...