我有一個運行良好的 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
uj5u.com熱心網友回復:
呼叫 API 時,需要將完整路徑 URL 傳遞給fetch或axios才能正常作業,但有一些要點需要提及。
所有 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
uj5u.com熱心網友回復:
您應該在 axios.get() 方法中提供完整的 URL。例如-“HTTP://localhost:port/api_path”。
為什么只有組態檔 API 弄亂你,因為你的路由器中提到了組態檔路由
<Route path="/profile/:username">
<Profile />
</Route>
如果你有的話,你沒有使用任何通配符路由它會給每個 api 帶來問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322883.html
