Express JS会话在另一条路线中返回未定义

时间:2019-06-05 18:00:30

标签: express session routes

登录用户后,我想表示要在会话中设置该用户的ID,并且当我登录时,我应该能够检索该ID。当我在'/ login'路由中设置它时,它很好用,但是当我尝试在'/ check-logged-user'路由中检索它时,它返回未定义。 但是,我检查了几乎所有与此相关的解决方案,但没有一个解决了我的问题。

app.get('/check-logged-user', function(req,res) {
    console.log(req.session);
});

app.post('/login', urlencodedParser, async function(req,res) {

    try {

        let { email, password } = req.body;

        let data = await User.findOne({email: email});

        if(data) {
            let passwordCheck = bcrypt.compareSync(password, data.password);

            if(passwordCheck) {

                if(data.status == 'pending') {
                    res.status(200).send('pending');
                } else if(data.status == 'inactive') {
                    res.status(200).send('inactive');
                } else if(data.status == 'active') {

                    req.session.user = data.id;
                    req.session.save();
                    res.status(200).send('success');
                } else {
                    res.status(500).send('invalid');
                }

            } else {
                res.status(200).send('incorrect');
            }
        } else {
            res.status(200).send('incorrect');
        }
    } catch(error) {
        res.status(500).send('error');
    }

});

app.post('/register', urlencodedParser, async function(req,res) {

    try {

        let { firstname, lastname, email, phone, password, confirm_password } = req.body;
        let created_at = Func.curTimestamp();

        let userData = {
            firstname,
            lastname,
            email,
            phone,
            password: bcrypt.hashSync(password,10),
            status: 'pending',
            activation_code: Func.genRand(10),
            created_at: created_at,
            updated_at: created_at
        }

        let newUser = new User(userData);

        let { email_exists, phone_exists } = false;
        let password_match = true;

        let check_user_email = await User.findOne({email: newUser.email});
        let check_user_phone = await User.findOne({phone: newUser.phone});

        password_match = (password !== confirm_password) ? false: true
        email_exists = (check_user_email) ? true : false;
        phone_exists = (check_user_phone) ? true: false;

        if(!password_match) {
            res.status(200).send('not_match');
        } else if(email_exists) {
            res.status(200).send('email_exists');
        } else if(phone_exists) {
            res.status(200).send('phone_exists');
        } else {
            newUser.save(function(err,data) {
                if(!err) {

                    res.status(200).send('success');
                } else {
                    res.status(500).send('error');
                }
            });
        }
    }  catch(error) {
        res.status(500).send('error');
    }
});

0 个答案:

没有答案