Javascript `SyntaxError:await仅在尝试在节点rest api中注册用户时在异步函数`中有效
我试图在nodejsrestapi中创建一个寄存器路由,但每当我尝试将数据发送到db时,它都会显示一些错误,如Javascript `SyntaxError:await仅在尝试在节点rest api中注册用户时在异步函数`中有效,javascript,node.js,rest,authentication,restapi,Javascript,Node.js,Rest,Authentication,Restapi,我试图在nodejsrestapi中创建一个寄存器路由,但每当我尝试将数据发送到db时,它都会显示一些错误,如SyntaxError:await仅在异步函数中有效。 我知道这个错误是什么意思,但我不知道为什么会出现这个错误。 这是我的注册路线代码: router.post(“/register”),异步(req,res)=>{ const firstName=req.body.firstName; const lastName=req.body.lastName; const email=re
SyntaxError:await仅在异步函数中有效。
我知道这个错误是什么意思,但我不知道为什么会出现这个错误。
这是我的注册路线代码:
router.post(“/register”),异步(req,res)=>{
const firstName=req.body.firstName;
const lastName=req.body.lastName;
const email=req.body.email;
const phone=req.body.phone;
const-gender=req.body.gender;
const country=req.body.country;
const password=req.body.passwordHash;
bcrypt.hash(密码,10,(错误,哈希)=>{
如果(错误){
日志(“错误:+err”);
}否则{
const newUser=新用户({
名字,
姓,
电子邮件,
电话,
性别,,
国家,,
passwordHash:hash,
});
试一试{
const savedUser=wait newUser.save()
res.send(savedUser)
}捕捉(错误){
资源状态(400).发送(错误)
}
}
});
});
await
在(err,hash)=>
函数中。因此您需要async(err,hash)=>
,而不是async(req,res)=>
wait
在(err,hash)=>
函数中。因此,在bcrypt.hash()的回调中需要async(err,hash)=>
,而不是async(req,res)=>
。hash()add async before(err,hash)=>…@fonzane是的,这是我在下面的回答中所说的在bcrypt.hash()add async before(err,hash)=>…@fonzane是的,这是我在下面的回答中所说的