MERN栈登录API异常:后端返回正确但前端判断错误
问题分析与解决方案
问题根源
Axios 仅在后端返回 HTTP 状态码 ≥400 时才会抛出异常进入 catch 块。你的后端代码中,用户不存在的场景使用了默认200状态码的res.json('not found!!'),Axios会判定请求成功,因此无论凭据对错都会走try分支,导致始终提示登录成功。
修复步骤
1. 修正后端代码
确保所有登录失败的场景都返回错误状态码(如401/422/404):
app.post('/login', async (req, res) => { const { email, password } = req.body; const userDoc = await User.findOne({ email }); console.log(userDoc); if (userDoc) { const passOk = bcrypt.compareSync(password, userDoc.password) if (passOk) { res.json('passok') } else { res.status(422).json('wrong credentials') } console.log('user found'); } else { res.status(404).json('not found!!') console.log('not found!!') } })
2. 优化前端逻辑(可选)
增加后端返回内容的校验,避免意外情况:
async function handeLoginSubmit(e) { e.preventDefault(); try { const response = await axios.post('/login', { email, password }); if (response.data === 'passok') { alert('Login Successful') } else { alert('Login Failed!') } } catch (e) { alert('Login Failed!') } }
关键说明
- Axios的异常触发规则:只有HTTP响应状态码属于错误范围(4xx、5xx)时,才会进入
catch块。 - 后端需在业务逻辑失败时主动设置错误状态码,前端才能正确捕获异常。
内容的提问来源于stack exchange,提问作者Asad Ali
相关产品推荐
相关产品推荐

