How to check session in Node.js Express?

后端 未结 4 1874
悲哀的现实
悲哀的现实 2021-02-15 04:31

I try to check if session in Express 4 is exist:

if(req.session.user == undefined) {}

It gives me error:

 Cannot read property          


        
4条回答
  •  孤街浪徒
    2021-02-15 04:59

    You can't just create a session without any middleware (Im assuming this is what you've tried).

    Read up on the express-session middleware docs, found here:

    https://github.com/expressjs/session

    Basic implementation example:

    Create a session:

    app.use(session({
      genid: function(req) {
        return genuuid() // use UUIDs for session IDs
      },
      secret: 'keyboard cat'
    }))
    

    To read a session:

    // Use the session middleware
    app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
    
    // Access the session as req.session
    
    app.get('/', function(req, res, next) {
      var sess = req.session
      if (sess.views) {
        sess.views++
        res.setHeader('Content-Type', 'text/html')
        res.write('

    views: ' + sess.views + '

    ') res.write('

    expires in: ' + (sess.cookie.maxAge / 1000) + 's

    ') res.end() } else { sess.views = 1 res.end('welcome to the session demo. refresh!') } })

    There are a number of tutorials you can find online, e.g:

    https://www.thepolyglotdeveloper.com/2015/01/session-management-expressjs-web-application/

提交回复
热议问题