【发布时间】:2018-07-22 22:53:26
【问题描述】:
我使用 React.js 和 Express.js 作为网络服务器制作了我的网络应用程序。 React 在 package.json 中通过这个(现在)连接到 Express:
"proxy": "http://localhost:5000/"
在我的 Express 服务器中,我使用它来处理会话:
const cookieSession = require('cookie-session');
还有这个:
app.use(cookieSession({
name: 'parse-session',
secret: "SECRET_SIGNING_KEY",
maxAge: 15724800000
}));
所以当我使用登录到我的 API 时它工作正常,这是检查 currentUser 是否存在的代码:
return new Promise((resolve,reject)=>{
if(req.session.token){
console.log(req.session.token);
request({
uri:'http://myserver.herokuapp.com/parse/users/me',
headers: {
'X-Parse-Application-Id': 'my-app-id',
'X-Parse-Session-Token': req.session.token
},
json:true
}).then((userData) => {
if(userData){
resolve(userData);
}
}).catch((error) => {
reject(error);
});
}
并且在 React 中使用这个调用没有问题:
fetch('/user',{credentials:'include'})
.then((response)=>{
return response.json();
})
.then((body)=>{
if(body.user){
this.setState({logIn:true});
}
}).catch((error)=>{
console.log('My error:',error);
});
问题是当我尝试注销时:我在 React 上执行此操作:
axios.post('/logout').then((res)=>{
console.log(res);
}).catch((err)=>{
console.log(err);
});
这是在 Express 上注销:
app.post('/logout',(req,res)=>{
if(req.session){
req.session.destroy((error)=>{
if(error){
console.log(error);
}
});
}
});
这给了我这个错误信息:
TypeError: req.session.destroy is not a function
为什么?我已经看到 destroy() 是一个函数。我也尝试过输入:req.session = null,但是,当您在承诺后调用以检查会话是否存在时,它当前处于活动状态。
为什么?我该如何解决呢?
谢谢
【问题讨论】:
-
你试过
delete req.session;吗?此外,如果您在任何销毁方法之后看到会话,请记录内容,它可能实际上已被销毁并重新生成,因此您可能有一个空会话。 -
@ruedamanuel 我也试过把 req.session = null.. 它为 null,但如果我尝试重做承诺,它会重新生成会话令牌
-
如果重新生成的会话令牌未通过 express 进行身份验证,那么应该没问题,您已有效注销,我不确定在这种情况下您的问题是什么。
-
@ruedamanuel 我不知道为什么它会继续重新生成,删除所有的唯一方法是删除浏览器中的 cookie ......是否有可能令牌也保存在 react 客户端应用程序中?
-
您是否尝试过使响应对象中的 cookie 无效? expressjs.com/en/4x/api.html#res.clearCookie
标签: node.js reactjs express session