Node.js - Session doesn't persist through res.redirect()

前端 未结 5 1188
甜味超标
甜味超标 2021-02-09 01:37

I\'m (almost) successfully using Node.js with Express and Redis to handle sessions.

The problem I\'m having is that the session is not kept when I use res.redirect

相关标签:
5条回答
  • 2021-02-09 01:37

    Your code looks pretty solid, but is there a reason you're using client.end()? It forcibly closes the redis connection and is not clean. I don't think you need it at all:

    https://github.com/mranney/node_redis/issues/74

    I am not sure about the underlying architecture for connect-redis, but I'm wondering if calling client.end is what's resetting your sessions. What happens if you take those out?

    0 讨论(0)
  • 2021-02-09 01:51

    Surely you need to save that session in some way, this might work.

    req.session.regenerate(function(){
        req.session.username = username.toString();
        res.redirect('/home');
    });
    
    0 讨论(0)
  • 2021-02-09 01:56

    Alright, I found the solution. The problem is that the time in maxAge was added to the current date. So, in the browser side, the cookie was set to expire at the GMT time shown.

    The problem was the following : I use a virtual machine to test node.js, and, you know... sometimes, you suspend your machine.

    Well, what happened is that the machine's time was two days late. So, whenever the cookie was set on the server side, the client side thought the cookie was already expired, since my host machine was not two days late.

    Another stupid outcome.

    0 讨论(0)
  • 2021-02-09 02:01

    I was having a similar problem in that I was setting something on the session that was not persisting outside the app.get() it was set in.

    My problem turned out to be that I was not doing a res.redirect() at the end of my app.get(). Looks like I was setting something on a request object and then allowing it to get garbage collected.

    I added a res.redirect( '/nextmethod' ) and the data persists just fine.

    0 讨论(0)
  • 2021-02-09 02:04

    Did you try with different browsers ? Are you keeping the same session id between page redirects ?

    You could add req.session.cookie.expires = false; before redirecting...

    0 讨论(0)
提交回复
热议问题