TheStuntback46
TheStuntback46

Reputation: 47

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

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.

Upvotes: 4

Views: 4439

Answers (2)

Vala Khosravi
Vala Khosravi

Reputation: 2570

I was using next.config.js to handle my proxy to my API server. and I was facing the same error. Because my API routes were like http://172.17.19.79:8000/api/job/ so I changed my next.config.js to code bellow:

module.exports = {
    async rewrites() {
        return [{
            source: '/api/:path*',
            destination: 'http://localhost:8000/api/:path*/'
        }]
    }
}

Upvotes: 0

Naveen Vignesh
Naveen Vignesh

Reputation: 1357

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.

Upvotes: 5

Related Questions