How to check session in Node.js Express?

后端 未结 4 2384
小蘑菇
小蘑菇 2021-02-15 04:53

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:10

    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 :)

提交回复
热议问题