Express change session every request

后端 未结 5 1845
夕颜
夕颜 2021-02-11 01:52

I have a function to login

app.post(\'/doLogin\', function(req,res){
        db.users.findOne({username: req.body.username}, function(err, user) {
            if         


        
5条回答
  •  长情又很酷
    2021-02-11 02:26

    Maybe there are some asynchronous errors in your code. Every time you have the asynchronous operation(like a callback), you should make sure that your rest code is executed after the callback function, so you may put the code into the callback function. Just like this:

    db.users.findOne({username: req.body.username}, function(err, user) {
      if( err ) {
        console.log("Login fail");
      } 
      else if (user != null) {
        if (req.body.password == user.password) {
          req.session.user_role = "user";
          req.session.save();
          res.send({redirect: "/"});
        } else {
          req.session.user_role = "null";
          console.log("Wrong login");
          res.send({redirect: "/"});
        }
      }
    });
    

    And the app.get should look like:

    app.get('/', function(req,res){
      redis.get('sess:' + req.session.id, function(err, result){
        console.log("Get session: " + util.inspect(JSON.parse(result),{ showHidden: true, depth: null }));
        if ((req.session.user_role == "user")) {
          console.log("Logged in");
        } else {
          console.log("Logged out");
        }
      });
    });
    

提交回复
热议问题