简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'email') with registration

I have problem with my if. There is my code: `

app.post('/register', redirectHome, async (req, res, next)=>{
    try{
        const email = req.body.email;
        let password = req.body.password;

        emaildb = await db.getUserByEmail(email);

        const isValidEmail = compareSync(email, emaildb.email);
        
        if(isValidEmail){
            err_msg = 'registration done';
            return res.render('register.ejs', {err_msg: err_msg});
            
        }
        else{
            err_msg = 'User already exists!';
            return res.render('register.ejs', {err_msg: err_msg});
        }

`

There is probably issue with compare, because when I write existing in db email I see "User already exists." and also when I write not existing in db email I see "User already exists.". So my if condition doesn't work well.

Consider a case that you do not have an user with a given email, for which emaildb is null or undefined. Then when you are calling the function compareSync(email, emaildb.email), here emaildb.email is undefined, for which you are not able to compare email and emaildb.email and throws "cannot read properties of undefined", also returning false.

 try{
        const email = req.body.email;
        let password = req.body.password;
    
        emaildb = await db.getUserByEmail(email);
        
        if(!emaildb){
           // do your work since no user exist with given email
           // return
        }
        else{
            err_msg = 'User already exists!';
            return res.render('register.ejs', {err_msg: err_msg});
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM