Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: Cannot read properties of undefined (reading 'password') NodeJS

When I try to use an invaild email adress in the Login form, the app crashes saying: Cannot read properties of undefined (reading ‘password’).

You can see my auth.js‘s Login part below:

exports.login = async (req, res) => {
    try {
        const { email, password } = req.body;

        if ( !email || !password ) {
            return res.status(400).render('login', {
                message: 'Please provide an email and password.'
            })
        }

        db.query('SELECT * FROM users WHERE email = ?', [email], async (error, results) => {
            console.log(results);
            if( !results || !(await bcrypt.compare(password, results[0].password) ) ) {
                res.status(401).render('login', {
                    message: 'Email or password is incorrect.'
                })
            } else {
                const id = results[0].id;

                const token = jwt.sign({ id }, process.env.JWT_SECRET, {
                    expiresIn: process.env.JWT_EXPIRES_IN
                });

                console.log('The token is: ' + token);

                const cookieOptions = {
                    expires: new Date(
                        Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
                    ),
                    httpOnly: true
                }

                res.cookie('jwt', token, cookieOptions);
                res.status(200).redirect("/");
            }
        })

    } catch (error) {
        console.log(error);
    }
}

It should show the same line that I can see when I use an incorrect password (That part works just fine).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

message: 'Email or password is incorrect.'

>Solution :

If the email is invalid, the query will return an empty array, not an undefined, meaning that your check is wrong – you should check the length of the array.

Of course, you can always leave the check that result is defined just to be on the safe side:

if( !results || !results.length || !(await bcrypt.compare(password, results[0].password) ) ) {
    res.status(401).render('login', {
        message: 'Email or password is incorrect.'
    });
} else {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading