如何使用React Router从React.js的子路径修复错误的代理重定向? [英] How to fix wrong proxy redirection from sub path from React.js using React Router?
问题描述
我正在使用React Router制作一个多页面的应用程序,并且正在使用Node作为后端. 节点在端口3000上工作,在端口3001上工作. 我已经在前端(React)的package.json中设置了代理. 我的API可在localhost:3000/api/上访问 因此,我使用axios从前端(端口:3001)获取或发布的内容如下:
I'm making a multi-pages app with React Router and I'm using Node for the backend. Node is working on the port 3000 and React on the port 3001. I have set up a proxy in package.json of the front-end(React). My API is reachable on localhost:3000/api/ So my get or post from the frontend(port:3001) with axios look like this:
axios.post('api/login/',{data........})
它在像/item或/example这样的父路径下运行良好 http://localhost:3001/xxxxxx/ ... 我可以在端口3000上访问/api/login.
It is working perfectly from a parent path like /item or /example http://localhost:3001/xxxxxx/ ... I can reach my /api/login on port 3000.
但是从诸如 http://localhost:3001/another/ex/之类的子路径中,或者 http://localhost:3001/xxxxxx/example/ ...我在控制台中看到获取或发布请求发送到 http://localhost:3001/xxxxxx/example/api/login 在这种情况下,代理无法正确重定向.
But from a subpath like http://localhost:3001/another/ex/ or http://localhost:3001/xxxxxx/example/ ... I see in the console the get or post request is sent to http://localhost:3001/xxxxxx/example/api/login In those cases, the proxy doesn't redirect properly.
我已经找到了避免子路径的解决方案,但是我想知道到底发生了什么,什么解决方案?
I have found the solution to avoid sub path but I would like to know what exactly is happening and what is the solutions?
提前感谢您的帮助!
<Router history={history}>
<NavBar history={history} refresh={this.state.refresh}/>
<Switch>
<Route exact path="/" render={(props) => <MainPage history=
{history} />}/>
<Route exact path="/item" history={history} component=
{ComponentX1} />
<Route exact path="/example" history={history} component=
{ComponentX2} />
<Route exact path='/another/ex' history={history} component=
{ComponentY1}/>
<Route exact path='/xxxxxx/example' history={history} component=
{ComponentY2}/>
</Switch>
<Footer/>
</Router>
我想了解发生了什么事.
I would like to understand what is happening.
推荐答案
使用必须具有这样的路径.
Use must have the path as such.
axios.post("/api/login", { ...data }) // Included '/' at the beginning
还要检查 package.json 中的代理服务器是否如此
Also, check if proxy in package.json is as such
...
proxy: 'http://localhost:3000' // not '/' at end.
...
如果您对我的评论有任何疑问.
If you have any doubts ping me in comments.
这篇关于如何使用React Router从React.js的子路径修复错误的代理重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!