UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of undefined

Viewed 535

This is my login code. Unhandledpromises occour while comparing Users input password and stored password.

exports.login = (req, res) => {
  try {    
    const {email, password} = req.body
    console.log(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(error)
        console.log(results)
        if( !results || !(await bcrypt.compare(password, results[0].password)) ) {
          res.status(401).render('login', {
            message: 'Email or Password is Incorrect'
          })
      }
     })

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

Console.log(error) is null..

Updated database

console.log

1 Answers

I'd suggest you to promisify db.query so you can await it, the errors will then be properly caught in the catch block, and your code will be flattened.

Your error is caused by results[0] which is undefined when trying to access its password property, which means that results is an empty array.

The second argument of query should not be an Object but an Array, so replace { email } with [email]:

const {
    promisify
} = require('util');

const query = promisify(db.query.bind(db));

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'
            });
        }

        const results = await query('SELECT * FROM users WHERE email = ? ', [email]); // problem occur due to usage of curly brackets.
            
        if (!results || !(await bcrypt.compare(password, results[0].password))) {
            res.status(401).render('login', {
                message: 'Email or Password is Incorrect'
            });
        }

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