这是我的登录代码。比较用户输入的密码和存储的密码时,出现未处理的承诺。
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(错误)为空。.
答案 0 :(得分:1)
我建议您promisify
db.query
,以便您可以await
,然后将错误正确地捕获在catch
块中,并且您的代码将是扁平化。
您的错误是由试图访问results[0]
属性的undefined
引起的,password
表示results
是一个空数组。
query
的第二个参数不应为Object
,而应为Array
,因此,将{ email }
替换为[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);
}
}