很简单。我在我的 /user/login
路由中设置了一个 cookie:
if (rememberMe) {
console.log('Login will remembered.');
res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' });
}
else {
console.log('Login will NOT be remembered.');
}
我已经为 cookie-parser 设置了我的 secret :
app.use(cookieParser('shhh!'));
非常基本的东西。只要我能够检索存储在 cookie 中的任何内容,一切都运行良好:
app.use(function (req, res, next) {
if (req.signedCookies.user) {
console.log('Cookie exists!');
req.session.user = req.signedCookies.user;
}
else {
console.log('No cookie found.');
}
next();
});
这个中间件在其他任何东西之前被调用,所以为了论证“Cookie 存在!”如果 cookie 有效,则始终记录在我的控制台中。
问题是当我尝试删除 cookie 时。我试过 res.clearCookie('user')
, res.cookie('user', '', { expires: new Date() })
,我我尝试传递相同的标志(我传递给 /user/login
中的 res.cookie()
)。我尝试组合使用这些方法,但没有任何效果。
目前,我能够清除 cookie(并且不会收到“Cookie 存在!”日志消息)的唯一方法是清除我的浏览器历史记录。这是我的注销路线:
route.get('/user/logout', function (req, res, next) {
res.clearCookie('user');
req.session.destroy();
util.response.ok(res, 'Successfully logged out.');
});
好像我什至不能修改cookie值;我把
res.cookie('user', {}, { signed: true, httpOnly: true, path: '/' })
在我的注销路由中,但 cookie 值保持不变。
最佳答案
经过漫长而烦人的时间后,我意识到我的前端没有将 cookie 发送到终点,因为我正在尝试清除 cookie...
在服务器上:
function logout(req, res) {
res.clearCookie('mlcl');
return res.sendStatus(200);
}
在前端,
fetch('/logout', { method: 'POST', credentials: 'same-origin' })
添加“凭据:‘同源’”使 clearCookie 对我有用。如果未发送 cookie,则无需清除任何内容。
希望对您有所帮助。我希望我早点找到这个......
关于javascript - 无法删除 express 中的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38558150/