使用 HTTP 请求反应路由器嵌套路由 v5

时间:2020-12-22 11:55:21

标签: reactjs react-router-v4

我在 App.js 文件中使用 react-router 如下:

 <Route exact path="/category/:categoryId">
    <ProductLists />
 </Route>

被这样称呼:

<RouterLink to={`/category/${category.id}`}>
    {category.name}
</RouterLink>

但问题是,当我尝试在 ProductLists 组件内发出 HTTP 请求时,它试图将“类别”放在请求的开头。

这是发出请求的代码:

Axios.get(
`/api/resources/products/category-id/?categoryId=${categoryId}`,
{
  headers: {
    'Content-Type': CONTENT_TYPE_JSON_VALUE,
  },
}

所以不要这样做:

http://localhost:3000/api/resources/products/category-id/?categoryId=10a49ef4

它是这样做的:

http://localhost:3000/category/api/resources/products/category-id/?categoryId=10a49ef4

知道为什么在请求的开头插入“类别”吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

感谢@Yousaf,我找到了答案。

我只需要像这样添加 baseURL: '/'

Axios.get(
 `/api/resources/products/category-id/?categoryId=${categoryId}`,
 {
   baseURL: '/',
   headers: {
     'Content-Type': CONTENT_TYPE_JSON_VALUE,
  },
}

希望这会在未来对某人有所帮助