How to disable webpage caching in ExpressJS + NodeJS?

前端 未结 3 1713
心在旅途
心在旅途 2020-12-10 12:35

By default, my browser caches webpages of my ExpressJS app.

This is causing a problem to my login system (users not logged in can open old cached pages of logged in

3条回答
  •  孤城傲影
    2020-12-10 13:27

    There are two things to consider when dealing with cache in Express.js - ETag and Cache-Control headers.

    ETag (MDN reference)
    If you have dynamic content which does not benefit from ETags, it's best to disable it because it incurs small overhead with each request.

    app.set('etag', false)
    

    Cache-Control (MDN reference)
    To completely disable cache, use the following header:

    app.use((req, res, next) => {
      res.set('Cache-Control', 'no-store')
      next()
    })
    

    This header does not affect express.static() middleware. It handles cache in its own way.

提交回复
热议问题