使用Thunder Client测试后端登录接口时遭遇500内部服务器错误
登录接口500错误排查与修复
错误原因
你的登录接口返回500内部服务器错误的核心问题出在delete user.password()语句:
user.password是用户对象的属性,而非可调用的方法,加括号()会触发语法错误,错误被catch块捕获后通过next(e)抛出,最终返回通用服务器错误。
修复代码
将错误语句修改为删除属性的正确写法,同时推荐用更安全的方式排除密码字段:
app.post('/login', async (req, res, next) => { const { email, password } = req.body console.log(req.body); try { const user = await User.findEmail({ email }); console.log(user) if (!user) { return res.status(400).json({ message: "Invalid Credentials, Please registered" }); } const isMatchPassword = await bcrypt.compare(password, user.password) if (!isMatchPassword) { return res.status(400).json({ message: "Invalid Credentials, Please registered" }); } // 修正:删除属性无需加括号,或用解构赋值排除密码(更安全) const { password: _, ...userWithoutPassword } = user; console.log(userWithoutPassword); return res.status(200).json({ message: "Login Successfull", user: userWithoutPassword }); } catch (e) { next(e); } });
补充说明
- 用解构赋值排除密码字段,不会修改数据库返回的原始用户对象,比直接
delete user.password更稳妥。 - 调试时可查看服务器控制台的错误日志,能快速定位这类语法调用类问题。
内容的提问来源于stack exchange,提问作者President Jam
相关产品推荐
相关产品推荐

