簡體   English   中英

`SyntaxError: await is only valid in async function` 同時嘗試在節點 rest api 中注冊用戶

[英]`SyntaxError: await is only valid in async function` while trying to register a user in node rest api

我正在嘗試在我的 NodeJS rest api 中創建一個注冊路由,但是每當我嘗試將數據發送到數據庫時,它都會向我顯示一些錯誤,例如SyntaxError: await is only valid in async function . 我知道錯誤的含義是什么,但是不知道為什么會出現此錯誤。 這是我的注冊路線代碼:

 router.post("/register", async (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(password, 10, (err, hash) => { if (err) { console.log("error: " + err); } else { const newUser = new User({ firstName, lastName, email, phone, gender, country, passwordHash: hash, }); try { const savedUser = await newUser.save() res.send(savedUser) } catch (err) { res.status(400).send(err) } } }); });

有人可以幫幫我嗎?

await(err, hash) => function 內。 所以你需要async (err, hash) => ,而不是async (req, res) =>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM