React与Express集成时res.redirect不生效问题排查
问题:React+Express登录跳转失效问题
我用React做前端,Express搭建后端API。首次登录时将JWT令牌存储在Cookie中,再次登录时检查Cookie中是否存在令牌(暂未验证,仅需实现跳转逻辑),期望存在令牌时重定向至个人资料页,但该功能失效。网络标签页中可看到XMLHttpRequest请求,但跳转未触发,前端使用Axios发起GET请求。
初始代码
后端(Express路由)
loginRouter.get("/", async (req, res) => { try { const cookieFound = req.cookies["login-token"]; if (cookieFound) { res.redirect("profile"); } else { res.redirect("login"); } } catch (error) { console.log(error); res.status(500).json("Ooops something went wrong!"); } });
前端(React useEffect)
useEffect(() => { Axios.get("/login"); }, []);
问题原因
前端通过Axios发起的是AJAX请求,后端的res.redirect()只会作用于这个AJAX请求本身(让请求内部重定向到目标地址),但不会触发浏览器的页面跳转——浏览器不会自动根据AJAX请求的重定向响应来刷新或跳转页面,所以能看到请求,但页面无变化。
修改方案
修改后后端代码
loginRouter.get("/", async (req, res) => { try { const cookieFound = req.cookies["login-token"]; if (cookieFound) { res.send("/profile"); // 返回跳转目标路径 } else { res.send("/login"); // 补充未登录场景的返回值 } } catch (error) { console.log(error); res.status(500).json("Ooops something went wrong!"); } });
修改后前端代码
useEffect(() => { const checkLoginStatus = async () => { const response = await Axios.get("/login"); // 根据后端返回的路径手动触发页面跳转 window.location.href = response.data; }; checkLoginStatus(); }, []);
说明
- 后端不再直接发送重定向响应,而是返回需要跳转的具体路径字符串
- 前端在获取到后端返回的路径后,通过
window.location.href手动控制浏览器跳转,触发页面的实际跳转 - 补充了未登录时的返回逻辑,避免后端在无令牌时无响应返回
内容的提问来源于stack exchange,提问作者UnkownSomeone
相关产品推荐
相关产品推荐

