2
I’m having trouble recovering data from req.session
. I have a sub-router that manages the main route and use a middleware to manage the session. I add the data I want to record in the session, but when the client accesses the route again, the req.session
seems to be reset.
Filing cabinet main.js
:
const sessionConfig = {
id: uuid.v4(),
secret: "1234",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 30,
sameSite: true,
secure: process.env.ENV === 'prod',
sameSite: process.env.ENV === 'prod',
httpOnly: true,
}
}
router.use(session(sessionConfig))
antiSpam = (req,res,next)=>{
let nextSend = req.session.nextSend
let date = new Date()
if(nextSend == undefined){
next()
}
else{
if (nextSend < date){
next()
}
else{
res.status(500)
res.send()
}
}
}
router.post("/contato/send", antiSpam, (req,res)=>{
data = req.body.data[0]
Object.keys(data).map((obj)=>{
if(data[obj] === ""){
res.status(500)
res.send()
}
if(obj == "tipo"){
data[obj] = data[obj] == 'pac' ? "Paciente" : "Profissional"
}
})
date = new Date()
nextSend = new Date(date.setMinutes(date.getMinutes() + 30))
req.session.nextSend = nextSend
})
As you can see, I write the current date that the user accessed the route /contato/send
and before the user enters the route I have a middleware that checks whether the current date is longer than the date that was first accessed. I store this date in the variable nextSend
and put it on req.session
, but when will I access req.session.nextSend
he returns undefined
.
P.S.: I have made some logs and it appears that a new session is generated for each request made.
Logs:
Session {
cookie:
{ path: '/',
_expires: 2019-11-22T14:43:20.239Z,
originalMaxAge: 1800000,
httpOnly: true,
sameSite: true,
secure: true },
flash: {} }
Log do middleware antiSpam:
undefined
Log dentro da rota /contato/send:
2019-11-22T14:43:20.265Z
Session {
cookie:
{ path: '/',
_expires: 2019-11-22T14:43:25.659Z,
originalMaxAge: 1800000,
httpOnly: true,
sameSite: true,
secure: true },
flash: {} }
Log do middleware antiSpam:
undefined
Log dentro da rota /contato/send:
2019-11-22T14:43:25.662Z
Recalling that, in the first access of the user, the req.session.nextSend
must be undefined
, however any other access after the first must return the date that the customer accessed for the first time, in theory at least.
Try to change the
uuid.v4()
by some constant key, for example,sid
. Solves the problem?– Luiz Felipe