Postman请求Node.js+Express开发的登录接口返回400无法获取用户登录信息
问题根因&修复方案
1. 补全findByCredentials方法的返回值
你当前的findByCredentials静态方法在邮箱、密码全部校验通过后,没有返回查询到的user对象,导致路由逻辑中拿到的user为undefined,校验通过也会出现逻辑异常。在方法末尾补充返回逻辑即可:
/** * user login crendentials */ userSchema.statics.findByCredentials = async (email, password) => { const user = await User.findOne({ email }); if (!user) { throw new Error("Unable to login"); } const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { throw new Error("Unable to login"); } // 新增:校验通过后返回匹配的用户对象 return user };
2. 登录路由补充错误返回信息
你当前登录接口的catch块直接调用res.status(400).send(),没有返回任何错误内容,所以调试时无法定位具体报错原因。修改为返回错误信息即可:
/** * User login. */ router.post("/users/login", async (req, res) => { try { const user = await User.findByCredentials( req.body.email, req.body.password ); res.send(user); } catch (e) { // 新增:返回错误详情方便排查 res.status(400).send({ error: e.message }); } });
3. 额外排查项
- 检查Postman请求
/users/login时的请求体格式是否为JSON,参数名是否和代码中读取的email、password完全一致,拼写、大小写不能有偏差 - 确认创建用户的逻辑中,密码已经通过bcrypt加密后再存储,若存的是明文密码,bcrypt.compare会一直返回false触发报错
- 检查express是否配置了
express.json()中间件,否则无法解析POST请求的JSON格式请求体,会导致req.body.email、req.body.password为undefined
内容的提问来源于stack exchange,提问作者Alamin
相关产品推荐
相关产品推荐

