如何在使用Redux的MERN应用中展示后端返回的登录错误信息
问题修复方案
梳理所有导致无法正常获取错误提示的问题,逐一修改即可:
1. 修复后端接口缺失return的问题
后端signin接口中密码校验失败的响应没有加return,会导致后续逻辑继续执行,重复发送响应,前端无法正常捕获错误:
const signin = async (req, res) => { const { email, password } = req.body; try { const existingUser = await User.findOne({ email }); if (!existingUser) return res.status(404).json({ message: "用户不存在" }); const isPasswordCorrect = await bcrypt.compare( password, existingUser.password ); // 此处补充return,阻止后续逻辑执行 if (!isPasswordCorrect) return res.status(404).json({ message: "账号或密码错误" }); const token = jwt.sign( { email: existingUser.email, id: existingUser._id }, "test", { expiresIn: "1h" } ); res.status(200).json({ result: existingUser, token }); } catch (error) { res.status(500).json({ message: "服务端异常,请稍后重试" }); } };
2. 修复authReducer的状态返回逻辑错误
原reducer返回格式错误,将原state嵌套到了新state的state属性下,且错误信息和用户登录信息共用authData字段会产生冲突,修改如下:
// 初始化状态新增errorMessage字段单独存储错误信息 const authReducer = (state = { authData: null, errorMessage: null }, action) => { switch (action.type) { case "AUTH": localStorage.setItem("profile", JSON.stringify({ ...action?.data })); // 展开原state,不要把state作为key嵌套,同时清空历史错误信息 return { ...state, authData: action?.data, errorMessage: null }; case "LOGOUT": localStorage.clear(); return { ...state, authData: null, errorMessage: null }; case "ERROR": // 错误信息存入单独字段,避免覆盖用户登录数据 return { ...state, errorMessage: action?.data }; default: return state; } }; export default authReducer;
3. 补全signup action的错误分发逻辑
原signup的catch分支没有分发错误事件,注册场景下无法拿到错误提示:
export const signup = (formData, history) => async (dispatch) => { try { const { data } = await api.signUp(formData); dispatch({ type: "AUTH", data }); history.push("/"); } catch (error) { console.log(error); // 补全错误分发,添加兜底错误提示避免读取属性报错 dispatch({ type: "ERROR", data: error.response?.data?.message || "操作失败,请稍后重试" }); } };
4. 前端组件读取错误信息渲染
在登录表单组件中通过useSelector从Redux获取错误信息,渲染到页面对应位置即可:
// 导入useSelector import { useSelector } from 'react-redux'; // 组件内获取错误信息 const errorMessage = useSelector(state => state.auth.errorMessage); // 表单区域渲染错误提示 return ( <div className="login-form"> {/* 错误提示区域 */} {errorMessage && <p style={{color: 'red', marginBottom: '12px'}}>{errorMessage}</p>} {/* 其余表单代码 */} <form onSubmit={handleSubmit(onSubmit)}> {/* 表单字段代码 */} </form> </div> )
修改完成以上4个点即可正常获取后端返回的错误信息并展示到前端页面。
内容的提问来源于stack exchange,提问作者r121
相关产品推荐
相关产品推荐

