
[英]req.session content disapear when trying to access it on another route
[英]Trying to access express req.session.variable declared in one route from another route via post method
我假设每个节点应用程序只有一个 session 变量,我试图从另一条路线访问 session object 中设置的值
请帮我解决这个问题
app.post(/OTP) 一条路线
function OTPgenerator(req,res,next){
var string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let OTPvalue='';
// Find the length of string
var len = string.length;
for (let i = 0; i < 8; i++ ) {
OTPvalue += string[Math.floor(Math.random() * len)];
}
console.log(OTPvalue,"OTP value");
req.OTP=OTPvalue;
req.session.OTP=OTPvalue;
req.session.save();
console.log(req.session); //this gives me value of session having OTP in it
next();
app.post('/OTP',OTPgenerator,(req,res)=>{
const OTP={
username:req.body.username,
useremail:req.body.useremail,
OTP:req.OTP
}
confirmation_email(OTP)
.then((resp)=>{
console.log("this is from the user info ",resp);
res.send(req.session);
})
.catch((err)=>{
console.log("this is the error ",err);
})
})
另一条路线(/提交)
app.post('/submit',
(req,res)=>{
console.log(req.session,"session") //the session here doesn't contain value of defined before
if(req.body.OTP!=null){
if(req.session.OTP===req.body.OTP){
const data=new userdata({
_id:mongoose.Types.ObjectId(),
username:req.body.username,
userpassword:req.body.userpassword,
userage:req.body.userage,
useremail:req.body.useremail
})
connectiondb()
.then(async(resp)=>{
console.log("Result of the connection",resp);
await data.save()
.then(resp=>{
console.log("this is response",resp);
res.status(200).send("data successfully saved")
})
.catch(err=>{
console.log("data is not saved ",err)
})
})
.catch(err=>{
console.log("thei si the error ",err);
res.sendStatus(500);
})
}
else if(req.body.OTP===''){
console.log("OTP cannot be null");
res.status(422);
}
else{
console.log('OTP is invalid');
res.status(422).send(req.session);
}
}
else{
res.status(500);
}
})
//for signin
这是我的 session object 配置
const db='mongodb+srv:xxxxx';
const obj={
useNewUrlParser:true,
useUnifiedTopology:true
}
const connection=mongoose.createConnection(db,obj);
const sessionStore=new MongoStore({
mongooseConnection:connection,
collection:'usersessions'
})
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: false,
store: sessionStore,
cookie:{
secure:true
}
}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.