【发布时间】:2021-02-06 05:04:48
【问题描述】:
我使用 node.js 作为后端并为前端做出反应。我正在使用 express-session 进行会话管理。这是我的注册功能,它是从按钮单击时的反应中调用的。它基本上使用 fetch 调用节点后端 api。
signup = ()=>{
if(this.state.tnc){
fetch(config.BASE_URL+"/api/signup",{
method:'POST',
headers:{
'Content-Type':'application/json',
},
body:JSON.stringify(this.state)
})
.then(res=>res.json())
.then(res=>{console.log(document.cookie);console.log(res)})
}
else{
window.alert('Please Accept the Terms and Conditions.')
}
}
这就是我在后端初始化会话的方式
router.use(session({
secret:'secret',
resave: false,
saveUninitialized: true,
cookie:{
httpOnly:true,
maxAge : 3600000,
sameSite : true
},
name:'_demo'
}))
这是后端的注册函数,在注册 api 调用时调用
signup : (req, res)=>{
const sess = req.session
SignUp.findOne({
where:{phoneNumber:req.body.phoneCode+req.body.phoneNumber}
}).then(result=>{
if(result){
res.send({status:'Success',data:'User Exists'})
}
else{
const user = SignUp.build({
fullName:req.body.fullName,
email:req.body.email,
phoneNumber:req.body.phoneCode+req.body.phoneNumber,
aadharNumber:req.body.aadharNumber,
city:req.body.city,
state:req.body.state,
zipCode:req.body.zipCode,
country:req.body.country
});
user.save().then(result=>{
sess.userId = result.getDataValue('id')
res.send({status:'Success',data:result.getDataValue('id')})
})
}
})
【问题讨论】:
-
您的会话 ID 已作为
_democookie 发送到浏览器。您还期望在浏览器中获得什么? -
我在标题中得到它,但是当我在 cookie 部分的开发工具中看到时,我没有看到正在设置的 cookie。另外,当我打印 document.cookie 时,它也没有打印出来。
-
将
httpOnly的值更改为false。否则浏览器不会让您从 JS 代码访问 cookie
标签: node.js reactjs express session cookies