Expressjs不会销毁会话

我有一个骨干视图,它发送一个Ajax调用服务器来删除一个会话。

在服务器上触发以下事件:

app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { res.clearCookie('connect.sid', { path: '/' }); res.send('removed session', 200); }); } else { res.send('no session assigned', 500); } }); 

奇怪的是,我可以多次按下注销button,而不会得到一个HTTP 500的错误代码。 铬也显示我仍然存在一个cookie。

出了什么问题?

问候

编辑

我发现这不是一个会话问题,而是一个cookie。 我添加res.clearCookie到路线。 不幸的是,行为(cookie,会话保持活跃)没有改变

编辑2 :我现在res.clearCookie一些参数=> res.clearCookie('connect.sid',{path:'/'}); 现在至lesscookie在浏览器中消失了。 但会议似乎仍然可用。 或者至less我可以多次呼叫注销路线,即使req.session也应该是错误的

编辑3:我现在从redis中删除所有会话,并重新启动一切(redis,节点,浏览器)。 比我再次login并注销。 这个工作到目前为止,但是当我用F5来翻页时,我得到一个新的会话。 为什么?

为了集中所有意见,我写了一个答案:

因为express总是为客户创build一个会话和一个cookie,所以我们不得不采取一种不同的方法来检查是否有会话。

这部分处理login

 app.post('/session', function(req, res) { User.findOne({ username: req.body.username }) .select('salt') // my mongoose schema doesn't fetches salt .select('password') // and password by default .exec(function(err, user) { if (err || user === null) throw err; // awful error handling here // mongoose schema methods which checks if the sent credentials // are equal to the hashed password (allows callback) user.hasEqualPassword(req.body.password, function(hasEqualPassword) { if (hasEqualPassword) { // if the password matches we do this: req.session.authenticated = true; // flag the session, all logged-in check now check if authenticated is true (this is required for the secured-area-check-middleware) req.session.user = user; // this is optionally. I have done this because I want to have the user credentials available // another benefit of storing the user instance in the session is // that we can gain from the speed of redis. If the user logs out we would have to save the user instance in the session (didn't tried this) res.send(200); // sent the client that everything gone ok } else { res.send("wrong password", 500); // tells the client that the password was wrong (on production sys you want to hide what gone wronge) } }); }); }); 

这是login部分让我们去注销:

 app.delete('/session', function(req, res) { // here is our security check // if you use a isAuthenticated-middleware you could make this shorter if (req.session.authenticated) { // this destroys the current session (not really necessary because you get a new one req.session.destroy(function() { // if you don't want destroy the whole session, because you anyway get a new one you also could just change the flags and remove the private informations // req.session.user.save(callback(err, user)) // didn't checked this //delete req.session.user; // remove credentials //req.session.authenticated = false; // set flag //res.clearCookie('connect.sid', { path: '/' }); // see comments above res.send('removed session', 200); // tell the client everything went well }); } else { res.send('cant remove public session', 500); // public sessions don't containt sensible information so we leave them } }); 

希望这可以帮助