react-router 是否与 API Url 混淆?

IT技术 node.js reactjs express axios react-router
2021-05-08 17:10:50

我有一个运行良好的 API,但是当我将它与 react 一起使用时,get 请求转到

/api/profile/posts/profile/matt

而它应该去:

/api/posts/profile/matt

代理设置localhost:8000/api为 ,当使用 react 时,它适用于其他 API。

调用 API 的代码(只有配置文件一个不起作用,其余一切正常,即使配置文件在我使用绝对 URL 时也能工作):

const res = username 
            ? await axios.get("posts/profile/"+username)
            : await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");

路线代码:

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route path="/login">
          <Login />
        </Route>
        <Route path="/register">
          <Register />
        </Route>
        <Route path="/profile/:username">
          <Profile />
        </Route>
      </Switch>
    </Router>
  )
}

我和这个用户也有类似的问题:如何防止 React-router 弄乱你的 API url

2个回答

当您调用 API 时,您需要将完整路径 URL 传递给fetchaxios才能正常工作,但有一些要点需要提及。

所有 API 都有两部分:基本 URL(不变)+其他部分

例如: https://someAddress.com/api/posts/profile/matt

基本 URL 在https://someAddress.com/api/这里。

Axios 使用一个baseURL参数来调用您的 API,而无需在每个 API 调用中指定:

axios.defaults.baseURL = 'https://somwAddress.com/api/;

现在,只需调用您的 API:

axios.get("posts/profile/" + username)

它请求完整的 URL: https://someAddress.com/api/posts/profile/username

您应该在 axios.get() 方法中提供完整的 URL。例如-“HTTP://localhost:port/api_path”。

为什么只有配置文件 API 弄乱您,因为您的路由器中提到了配置文件路由

    <Route path="/profile/:username">
        <Profile />
    </Route>

如果你有的话,你没有使用任何通配符路由它会给每个 api 带来问题