通过Node.js代理服务器调用React路由失效问题排查
问题解决:Node.js代理无法跳转至React Login组件
问题原因
http-proxy的target参数指定的是目标服务器的根地址,而非具体前端路由路径。当你把target设为http://localhost:3000/login时,代理会直接请求React开发服务器的/login后端路径,但React开发服务器默认仅对根路径/返回index.html,其他未配置的后端路径会返回404,自然无法触发前端路由渲染Login组件。
解决方案
保持target为http://localhost:3000,通过修改请求的url来指向前端路由/login,让React的前端路由接管路径匹配。
修改后的代理代码:
app.use((req, res, next) => { const userCookie = req.cookies.user; const url = req.originalUrl; var pattern = /\/api\//; if (userCookie ) { //if cookie is present if (pattern.test(url)) { next(); console.log("Contains API") } else { //if url doesnt contains /api proxy.web(req, res, { target: "http://localhost:3000" }); console.log("/login:3000"); } }else if(url== '/api/login'){ console.log("login"); next(); } else { // if cookie not set if (pattern.test(url)) { //if url contains /api res.status(401).send("plz login in"); console.log("login Required"); } else { console.log("http://localhost:3000/login"); // 修改请求路径为/login,保持target为React服务器根地址 req.url = '/login'; proxy.web(req, res, { target: "http://localhost:3000" }); } } });
补充说明
如果需要更灵活的路径重写,也可以使用http-proxy的pathRewrite配置项,比如:
proxy.web(req, res, { target: "http://localhost:3000", pathRewrite: { '^.*$': '/login' } // 将所有请求路径重写为/login });
这样修改后,代理会把请求转发到React服务器的根路径,同时传递/login的路径参数,React的前端路由就能正确匹配并渲染Login组件了。
内容的提问来源于stack exchange,提问作者Atharv Arolkar
相关产品推荐
相关产品推荐

