[英]Console Error: await is only valid in async functions and the top level bodies of modules
I am making a login functionality in nodejs and there i want to store the password in mysql db by hashing it: I am using bcrypt library.我正在nodejs中创建登录功能,我想通过散列将密码存储在mysql db中:我正在使用bcrypt库。
bcrypt.hash(password, 10, function(err, hash) {
console.log(hash);
});
Above code working fine for me but if i want to use like below one using await上面的代码对我来说很好,但是如果我想像下面这样使用 await
let hashedPassword = await bcrypt.hash(password,10);
its showing below error as它显示以下错误为
let hashedPassword = await bcrypt.hash(password,10);
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
Note: My aim is to use it in async way so using await.注意:我的目标是以异步方式使用它,所以使用 await。 And the doubt is,
怀疑是,
Below is the total controller code for detailed info:以下是详细信息的总控制器代码:
const db = require("../connection");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
exports.register = (req,res) => {
const {name, email, password, cpassword} = req.body;
db.query('SELECT * FROM users WHERE email=?', [email],(error,result)=>{
if(error){
console.log(error);
} else if(result.length > 0){
return res.render('signup',{
message:'Email already exists!'
})
} else if(password !== cpassword){
return res.render('signup',{
message: 'Passwords do not match!!'
});
}
let hashedPassword = await bcrypt.hash(password,10);
console.log(hashedPassword);
// bcrypt.hash(password, 10, function(err, hash) {
// console.log(hash);
// });
});
}
your register function is not asynchronous.您的注册功能不是异步的。 Try this:
尝试这个:
exports.register = async (req,res) => {
...rest of the code
}
The basic you have to understand in asynchronous function is to make a function async then use await, but your code there is no asynchronous function for which it will throw error.在异步函数中您必须了解的基本知识是使函数异步然后使用等待,但是您的代码没有异步函数会引发错误。 Hence you have to make the parent function as async type.
因此,您必须将父函数设为异步类型。 Updated code below
下面更新了代码
#previous code..
db.query('SELECT * FROM users WHERE email=?', [email], async (error,result)=>{
#other codes here..
let hashedPassword = await bcrypt.hash(password,10);
console.log(hashedPassword);
});
#next code..
This way you can use both ways of hash & salt这样你就可以使用哈希和盐的两种方式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.