Ken*_*den 6 javascript cookies node.js express
很简单 我在/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.');
}
Run Code Online (Sandbox Code Playgroud)
我已经为cookie解析器设置了秘密:
app.use(cookieParser('shhh!'));
Run Code Online (Sandbox Code Playgroud)
很基本的东西。只要我能够检索存储在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();
});
Run Code Online (Sandbox Code Playgroud)
在调用此中间件之前,请先声明“ Cookie存在!”。如果Cookie有效,则始终在控制台中登录。
问题是当我尝试删除Cookie时。我尝试了res.clearCookie('user'),,res.cookie('user', '', { expires: new Date() })并且尝试传递相同的标志(我传递给res.cookie()in /user/login)。我尝试使用这些方法的组合,但是没有任何效果。
当前,我能够清除Cookie(并且不会收到“ Cookie存在!”日志消息)的唯一方法是清除浏览器历史记录。我的登出路线如下所示:
route.get('/user/logout', function (req, res, next) {
res.clearCookie('user');
req.session.destroy();
util.response.ok(res, 'Successfully logged out.');
});
Run Code Online (Sandbox Code Playgroud)
似乎我什至无法修改cookie值;我放
res.cookie('user', {}, { signed: true, httpOnly: true, path: '/' })
在我的登出路线中,但Cookie值保持不变。
即使它不会帮助这个问题的作者,我希望这可以帮助某人。我遇到了同样的问题,我无法在使用 Express api 的 React 应用程序中删除 cookie。我使用了 axios,几个小时后我终于能够修复它。
await axios.post('http://localhost:4000/api/logout', { } , { withCredentials: true })
Run Code Online (Sandbox Code Playgroud)
{ withCredentials: true } 是什么让它对我有用。
这是我的快递代码:
const logOutUser = (req, res) => {
res.clearCookie('username')
res.clearCookie('logedIn')
res.status(200).json('User Logged out')
}
Run Code Online (Sandbox Code Playgroud)
从(广泛的)搜索和我脑海中突然出现的一个随机想法来看,答案是使用
res.clearCookie('<token_name>',{path:'/',domain:'<your domain name which is set in the cookie>'});
Run Code Online (Sandbox Code Playgroud)
IE
res.clearCookie('_random_cookie_name',{path:'/',domain:'.awesomedomain.co'});
Run Code Online (Sandbox Code Playgroud)
请注意. 这是在 cookie 中指定的,因为我们将它用于子域(您也可以将它用于不带点的子域,但使用它更安全)。
太长了;您必须在后端提供路由和域:,以便向前端中的同一端点发出请求。
经过漫长而烦人的时间后,我意识到我在尝试清除Cookie时,前端未将Cookie发送到终点。
在服务器上:
function logout(req, res) {
res.clearCookie('mlcl');
return res.sendStatus(200);
}
Run Code Online (Sandbox Code Playgroud)
在前端,
fetch('/logout', { method: 'POST', credentials: 'same-origin' })
Run Code Online (Sandbox Code Playgroud)
添加“凭据:'同源'”使clearCookie对我有用。如果未发送cookie,则无任何清除。
我希望这有帮助。我希望我早发现了这个...
即使它只是一个/logout端点,您仍然需要发送凭据。
// FRONT END
let logOut = () => {
fetch('logout', {
method: 'get',
credentials: 'include', // <--- YOU NEED THIS LINE
redirect: "follow"
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
}
// BACK END
app.get('/logout', (req, res) => {
res.clearCookie('token');
return res.status(200).redirect('/login');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6456 次 |
| 最近记录: |