ste*_*206 2 session node.js express reactjs
我使用React.js和Express.js作为Web服务器制作了我的webapp.React在package.json中与Express(现在)连接到Express:
"proxy": "http://localhost:5000/"
Run Code Online (Sandbox Code Playgroud)
在我的Express服务器中,我用它来处理会话:
const cookieSession = require('cookie-session');
Run Code Online (Sandbox Code Playgroud)
还有这个:
app.use(cookieSession({
name: 'parse-session',
secret: "SECRET_SIGNING_KEY",
maxAge: 15724800000
}));
Run Code Online (Sandbox Code Playgroud)
因此,当我使用登录到我的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);
});
}
Run Code Online (Sandbox Code Playgroud)
并且在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);
});
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试注销时:我在React上执行此操作:
axios.post('/logout').then((res)=>{
console.log(res);
}).catch((err)=>{
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
这是在Express上注销:
app.post('/logout',(req,res)=>{
if(req.session){
req.session.destroy((error)=>{
if(error){
console.log(error);
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
这给了我这个错误信息:
TypeError: req.session.destroy is not a function
Run Code Online (Sandbox Code Playgroud)
为什么?我已经看到destroy()是一个函数.我也尝试过:req.session = null但是,当你在承诺之后打电话来检查会话是否存在它当前还活着.
为什么?我怎么用来解决它?
谢谢
req.session.destroy是使用express-sessionnpm模块时使用的调用.但是,您正在使用cookie-session其当前版本中未定义的内容,req.session.destroy从而导致您获得的错误.
要在使用时销毁会话cookie-session,只需将其设置为null : req.session = null. 如果你决定express-session改用,那就行了req.session.destroy.
参考文献:
| 归档时间: |
|
| 查看次数: |
2088 次 |
| 最近记录: |