How to fix wrong proxy redirection from sub path from React.js using React Router?

☆樱花仙子☆ 提交于 2020-02-02 12:31:12

问题


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........})

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.

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?

Thanks in advance for your help!

<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.


回答1:


Use must have the path as such.

axios.post("/api/login", { ...data }) // Included '/' at the beginning

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.



来源:https://stackoverflow.com/questions/55907518/how-to-fix-wrong-proxy-redirection-from-sub-path-from-react-js-using-react-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!