【问题标题】:Is react-router messing with the API Url?react-router 是否与 API Url 混淆了?
【发布时间】:2021-12-04 03:22:47
【问题描述】:

我有一个运行良好的 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>
  )
}

这个用户也有类似的问题:How to prevent React-router from messing up your API url

【问题讨论】:

  • React Router 进行部分匹配。将路由定义为exact,或更改路由名称。
  • 你在哪里告诉 react 去寻找 /api/...?也许你在服务中保持不变......添加精确到路线应该可以正常工作
  • 我已经尝试添加 exact 但它不起作用,package.json 中的代理设置为 localhost:8000/api

标签: node.js reactjs express axios react-router


【解决方案1】:

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

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

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

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

【讨论】:

  • 通常不鼓励使用完整路径吗?我该如何解决这个问题,以便在不使用绝对 URL 的情况下将请求转到正确的路径?
【解决方案2】:

调用API时,需要将完整路径URL传递给fetchaxios才能正常工作,但有几点需要说明。

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

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

这里的基本网址是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

【讨论】:

  • 设置基本URL WORKED,我仍然感到困惑的是,当我已经在package.json中定义了代理(其中与应用程序中的其他获取/发布请求一起使用,除了获取配置文件发布一个),无论如何谢谢!
猜你喜欢
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多