如何修复React.js中使用React Router的子路径错误代理重定向?

4

我正在使用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>

我希望能够理解正在发生的事情。

2个回答

5

必须按照以下路径进行操作。

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

同时,请检查 package.json 中的代理是否正确

...
proxy: 'http://localhost:3000' // not '/' at end.
...

如果您有任何疑问,请在评论中留言联系我。

嗨,@Naveen Vignesh。感谢您抽出时间来回答问题。代理已正确设置,例如,对于api/login,它正在工作,因为我从localhost:3001/login在我的前端上进行调用,但是如果例如,我想要从user/login到达API的相同点,那么我的前端会尝试访问:localhost:3001/user/login/api/login而不是localhost:3000/api/login,在这种情况下,代理似乎无法正常工作。 - TheStuntback46
你需要在axios调用中加上前导斜线,就像@Naveen指出的那样。将axios.post('api/login/',{data........})修改为axios.post('/api/login/',{data........})。这样可以解决添加子路径至API调用的问题。 - Brandon Mitchell
1
@BrandonMitchell 这将解决问题,但背后的原因是什么?我想知道那里到底发生了什么,在添加斜杠之后它为什么能工作?为什么? - Zaif Warm
"// 在开头加入'/'。这行代码救了我的一天!" - Piyush Hirpara

0

我使用 next.config.js 处理我的代理到 API 服务器,但是我遇到了相同的错误。因为我的 API 路由类似于 http://172.17.19.79:8000/api/job/ ,所以我将我的 next.config.js 更改为以下代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接