How to check session in Node.js Express?

后端 未结 4 1875
悲哀的现实
悲哀的现实 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 05:15

    The issue you are facing is maybe you are not using the session middleware in ALL of your requests. You can check it the following way :

    1. Add this to all of your routes :

    app.use(session({ secret: 'keyboard cat',resave:false,saveUninitialized:false, cookie: { maxAge: 60000 }}));

    1. Authentication Route :

    router.post('/', function(req, res, next) {
      //login logic here
    
      //if login successfull
      req.session.user = username //your unique identifier
      req.send("Hurray! logged in");
    
      //else
      req.send("Credentials error");
    
    });

    1. Check in any route:

    router.get('/dashboard', function(req, res, next) {
      if (req.session.user)
        //do stuff here
      else
      //redirect to login page
    
    })

    This works :)

提交回复
热议问题