Node.js和Express会话处理 - 后退按钮问题

Pon*_*ono 17 session node.js express

我的Express应用程序中有一个禁区"/仪表板".我使用一个非常小的函数来限制访问:

app.get('/dashboard', loadUser, function(req, res){
  res.render('dashboard', {
    username: req.session.username
  });
});

function loadUser(req, res, next){
  if (req.session.auth) {
    next();
  } else {
    res.redirect('/login');
  }
};
Run Code Online (Sandbox Code Playgroud)

问题是当我通过调用注销用户时...

app.get('/logout', function(req, res){
  if (req.session) {
    req.session.auth = null;
    res.clearCookie('auth');
    req.session.destroy(function() {});
  }
  res.redirect('/login');
});
Run Code Online (Sandbox Code Playgroud)

...会话被杀死但是当我在浏览器中点击Back Button时,我从浏览器的缓存中获得了受限制的页面.这意味着'/ dashboard'上没有GET,也没有用户登录验证.

我尝试在元(Jade模板)中使用no-cache,但它仍然不起作用.

meta(http-equiv='Cache-Control', content='no-store, no-cache, must-revalidate')
meta(http-equiv='Pragma', content='no-cache')
meta(http-equiv='Expires', content='-1')
Run Code Online (Sandbox Code Playgroud)

任何人?

pky*_*eck 57

可悲的是乔希的回答对我不起作用.但经过一番搜索,我发现了这个问题:处理缓存和浏览器后退按钮的最佳方法是什么?

并通过了这个node.js/express问题的答案.您只需要更改以下行

res.header('Cache-Control', 'no-cache');
Run Code Online (Sandbox Code Playgroud)

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

现在,每次我使用浏览器后退按钮时,页面都会重新加载而不会被缓存.

*更新快递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
Run Code Online (Sandbox Code Playgroud)

  • 试试这个:app.use(function(req,res,next){res.header('Cache-Control','no-cache,private,no-store,must-revalidate,max-stale = 0,post-check) = 0,pre-check = 0'); next();}); (3认同)
  • 我有类似的问题。您到底在哪里添加那行代码? (2认同)

Jos*_*osh 7

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
  });
});
Run Code Online (Sandbox Code Playgroud)