我正在使用React Router制作一个多页应用程序,并且我正在使用Node作为后端。 Node正在3000端口上运行,React正在3001端口上运行。 我在前端(React)的package.json中设置了代理。 我的API可以通过localhost:3000/api/访问。 所以我的axios get或post从前端(端口:3001)看起来像这样:
axios.post('api/login/',{data........})
从父级路径如 /item 或 /example 完美运行。 http://localhost:3001/xxxxxx/ ... 我可以访问端口为 3000 的 /api/login。
但从子路径如 http://localhost:3001/another/ex/ 或 http://localhost:3001/xxxxxx/example/ ... 我在控制台中看到 get 或 post 请求被发送到 http://localhost:3001/xxxxxx/example/api/login 在这些情况下,代理没有正确重定向。
我已经找到了避免子路径的解决方案,但我想知道到底发生了什么以及有哪些解决方案?
提前感谢你的帮助!
<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>
我希望能够理解正在发生的事情。
axios.post('api/login/',{data........})
修改为axios.post('/api/login/',{data........})
。这样可以解决添加子路径至API调用的问题。 - Brandon Mitchell