NodeJS中await报错:仅在async函数及模块顶层有效,如何解决?
解决NodeJS登录模块中await语法错误问题
问题重现
在开发NodeJS结合MongoDB的用户登录注册功能时,login模块出现以下错误:
existingUser = await User.findOne({email: email}); ^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules.
相关代码
user-controller.js文件代码:
const User = require('../model/User'); const bcrypt = require('bcryptjs'); // next is used to move to the next middleware task const signup = async (req, res, next) => { const { name, email, password } = req.body; let existingUser; try { existingUser = await User.findOne({ email: email }); } catch (err) { console.log(err); } if (existingUser) { return res.status(400).jason({ message: 'User already exists! Login Instead' }) } const hashedPassword = bcrypt.hashSync(password); const user = new User({ name, email, password: hashedPassword, }); try { await user.save(); } catch (err) { console.log(err); } return res.status(201).json({ message: user }) }; const login = (req, res, next) => { const { email, password } = req.body; let existingUser; try { existingUser = await User.findOne({ email: email }); } catch (err) { return new Error(err); } if (!existingUser) { return res.status(400).json({ message: "User not found. Signup Please" }) } const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password); if (!isPasswordCorrect) { return res.status(400).json({ message: "Invalid Email / Password" }) } return res.status(200).json({ message: "Successfully logged in" }) } exports.signup = signup; exports.login = login;
解决步骤
- 核心问题修复:
login函数未标记为async,而await关键字仅能在async函数内部使用。修改login函数定义,添加async关键字:
const login = async (req, res, next) => { const { email, password } = req.body; let existingUser; try { existingUser = await User.findOne({ email: email }); } catch (err) { return res.status(500).json({ message: "Something went wrong" }); } if (!existingUser) { return res.status(400).json({ message: "User not found. Signup Please" }) } const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password); if (!isPasswordCorrect) { return res.status(400).json({ message: "Invalid Email / Password" }) } return res.status(200).json({ message: "Successfully logged in" }) }
补充:原代码中catch块返回new Error(err)无法向客户端返回有效错误响应,建议改为返回500状态码的JSON响应。
- 额外小问题修复:
signup函数存在一处拼写错误,res.status(400).jason应改为res.status(400).json,否则会导致响应失败。
内容的提问来源于stack exchange,提问作者Tech World
相关产品推荐
相关产品推荐

