javascript node express,注销后如何清除cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32114720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node express, how to clear cookie after log out
提问by Srle
Basically i'm doing redirect from a.example.com to www.example.com and i expect to be able to delete cookies on www.example.com (because cookie is created with .example.com as the cookie domain), but following code doesn't work.
基本上,我正在从 a.example.com 重定向到 www.example.com,我希望能够删除 www.example.com 上的 cookie(因为 cookie 是使用 .example.com 作为 cookie 域创建的),但是以下代码不起作用。
I know that this question seems like duplicate question, i tried everything from similar question but it doesn't work. See after the code what i already tried.
我知道这个问题似乎是重复的问题,我尝试了类似问题中的所有内容,但没有用。看看我已经尝试过的代码。
Using express 3.0.3 and node 0.10.32.
使用 express 3.0.3 和节点 0.10.32。
express session middleware
快速会话中间件
...
var cookiedata = {
domain : '.example.com',
originalMaxAge : null,
httpOnly : false
};
app.use(express.session({
store : ...,
secret : ...,
key : 'express.sid',
cookie : cookiedata
}));
...
logout function
登出功能
function logout(req, res){
...
req.session.destroy(function(){
req.session = null;
res.clearCookie('express.sid', { path: '/' });
res.redirect('https://www.example.com');
});
}
What i already tried from similar question
我已经从类似问题中尝试过的
So i put path : '/'
in express session middleware such as:
所以我放入path : '/'
了快速会话中间件,例如:
app.use(express.session({ ..., path : '/' });
No success.
没有成功。
- https://groups.google.com/forum/#!topic/express-js/PmgGMNOzhgM
Instead res.clearCookie i used: res.cookie('express.sid', '', {expires: new Date(1), path: '/' });
- https://groups.google.com/forum/#!topic/express-js/PmgGMNOzhgM
而不是 res.clearCookie 我使用: res.cookie('express.sid', '', {expires: new Date(1),小路: '/' });
No success.
没有成功。
回答by Tien Do
This is response.clearCookie of Express.JS (file response.js at line 749).
这是 Express.JS 的 response.clearCookie(文件 response.js 在第 749 行)。
var opts = merge({ expires: new Date(1), path: '/' }, options);
return this.cookie(name, '', opts);
If you set a breakpoint at this line you will see expires is reported at an invalid date. So instead of using response.clearCookie, just make it expire immediately like this one.
如果您在此行设置断点,您将看到在无效日期报告 expires。因此,与其使用 response.clearCookie,不如让它像这样立即过期。
response.cookie("express.sid", "", { expires: new Date() });
回答by Sandro Wiggers
This is working for me with cookie-parser
module:
这对我有用的cookie-parser
模块:
router.get('/logout', function(req, res){
cookie = req.cookies;
for (var prop in cookie) {
if (!cookie.hasOwnProperty(prop)) {
continue;
}
res.cookie(prop, '', {expires: new Date(0)});
}
res.redirect('/');
});