Node.js and Express session handling - Back button problem

后端 未结 4 1860
無奈伤痛
無奈伤痛 2020-12-23 19:04

I have a restricted area \'/dashboard\' in my Express application. I use a very small function to limit the access:

app.get(\'/dashboard\', loadUser, functi         


        
相关标签:
4条回答
  • 2020-12-23 19:37

    Simple solution is after clearing the session .. again redirect to the same route.. for example: route /sessionedpage has session variables .. after clicking logout button clear session variables by req.session.destroy(function() {}); after that you are tring to redirect home page ... INSTEAD of redirecting to home page.. redirect /sessionedpage (same route) ... Write if condition for /sessionedpage if(!res.sessions) then res.redirect('/home')

    0 讨论(0)
  • 2020-12-23 19:44
    app.get('/dashboard', loadUser, function(req, res){
      res.header('Cache-Control', 'no-cache');
      res.header('Expires', 'Fri, 31 Dec 1998 12:00:00 GMT');
    
      res.render('dashboard', {
        username: req.session.username
      });
    });
    
    0 讨论(0)
  • 2020-12-23 19:49

    Am using using Express ^4.16.3 and this worked for me as stated by @pkyeck.

    I added it to my routes like this and it worked fine:

    routes
    .use(function(req, res, next) {
    res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
            next();
              })
              .get('/login', function(req, res, next){
                  .....
    })
    
    0 讨论(0)
  • 2020-12-23 20:01

    Josh's answer sadly didn't work for me. But after some searching I found this question: What's the best way to deal with cache and the browser back button?

    and adopted the answer there to this node.js/express problem. You just have to change the following line

    res.header('Cache-Control', 'no-cache');
    

    to

    res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
    

    Now, everytime I use the browser back button, the page is reloaded and not cached.

    * update for express v4.x *

    // caching disabled for every route
    server.use(function(req, res, next) {
      res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
      next();
    });
    
    // otherwise put the res.set() call into the route-handler you want
    
    0 讨论(0)
提交回复
热议问题