How to fix wrong proxy redirection from sub path f

2020-07-23 08:57发布

问题:

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.