How to end a session in ExpressJS

前端 未结 9 835
小鲜肉
小鲜肉 2020-12-12 15:48

I feel like this has to be buried somewhere in the documentation, but I can\'t find it.

How do you close or end or kill (whatever) a session in ExpressJS?

相关标签:
9条回答
  • 2020-12-12 15:50

    use,

    delete req.session.yoursessionname;
    
    0 讨论(0)
  • 2020-12-12 15:50

    Session.destroy(callback)

    Destroys the session and will unset the req.session property. Once complete, the callback will be invoked.

    Secure way ↓ ✅

    req.session.destroy((err) => {
      res.redirect('/') // will always fire after session is destroyed
    })
    

    Unsecure way ↓ ❌

    req.logout();
    res.redirect('/') // can be called before logout is done
    
    0 讨论(0)
  • 2020-12-12 15:55

    Express 4.x Updated Answer

    Session handling is no longer built into Express. This answer refers to the standard session module: https://github.com/expressjs/session

    To clear the session data, simply use:

    req.session.destroy();
    

    The documentation is a bit useless on this. It says:

    Destroys the session, removing req.session, will be re-generated next request. req.session.destroy(function(err) { // cannot access session here })

    This does not mean that the current session will be re-loaded on the next request. It means that a clean empty session will be created in your session store on next request. (Presumably the session ID isn't changing, but I have not tested that.)

    0 讨论(0)
  • 2020-12-12 15:55
    req.session.destroy(); 
    

    The above did not work for me so I did this.

    req.session.cookie.expires = new Date().getTime();
    

    By setting the expiration of the cookie to the current time, the session expired on its own.

    0 讨论(0)
  • 2020-12-12 16:02

    The question didn't clarify what type of session store was being used. Both answers seem to be correct.

    For cookie based sessions:

    From http://expressjs.com/api.html#cookieSession

    req.session = null // Deletes the cookie.
    

    For Redis, etc based sessions:

    req.session.destroy // Deletes the session in the database.
    
    0 讨论(0)
  • 2020-12-12 16:04

    Never mind, it's req.session.destroy();

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