Why does the express session return 'Undefined'?

Asked

Viewed 345 times

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?

1 answer

3


Two things:

  • First I think in the cookie config, the field secure should be adjusted to false, at least that’s what I realized in my code. It worked and saved the session when the secure: false. The field secure should be used only in connection https, if not, if the connection is http, the cookie will not be displayed.
  • second, I correct your if date check to the default in milliseconds. Try to do something similar to my code below and try again. I hope to have helped.
    const sessionConfig = {
     id: "1",
     secret: "1234",
     resave: false,
     saveUninitialized: false,
     cookie: {
     maxAge: 1000 * 60 * 30,
     sameSite: true,
     secure: false, // ajustar para false em conexoes HTTP
     sameSite: true,
     httpOnly: true
     }
    };

    app.use(session(sessionConfig));

    app.get(
     "/oi",
     (req, res, next) => {
      let date = Date.now();
      let nextSend = req.session.nextSend;
      if (!nextSend) {
       return next();
      }
      console.log(nextSend, date)
      if (nextSend < date) { // para este if, ambas as datas devem estar em milisegundos
       console.log("eh menor!!!!!!!!!!!!!!!! Pode prosseguir.");
       return next();
      }
      console.log("===== Data atual:", new Date(Date.now()), "\n");
      console.log("===== Proxima data de envio:", new Date(req.session.nextSend), 
       "\n");
      return res.json({ message: "PERA AI" });
    },
    (req, res) => {
      req.session.nextSend = Date.now() + 18000; // 18 segundos apenas para teste
      res.sendFile("index.html", {
       root: path.join(__dirname, "views")
      });
     }
    );

Exit:
inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.