我有一個 MERN 堆疊應用程式,目前localhost:3000用于托管我的應用程式的反應端并localhost:8080托管它從中獲取資料的快速服務器。
我能夠從我的快速服務器呼叫某些 API,例如localhost:8080/shows從我的資料庫回傳所有節目。在反應方面,這是通過以下代碼完成的:
async function getAllShows(setShows, setLoading) {
const response = await fetch("/shows");
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
console.log(response);
const records = await response.json();
setShows(records.shows);
setLoading(false);
}
export default getAllShows;
這是呼叫我的用戶端點的幾乎相同的代碼:
async function getAllUsers(setUsers, setLoading) {
const response = await fetch("/users");
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
console.log(response);
const records = await response.json();
setUsers(records.shows);
setLoading(false);
}
export default getAllUsers;
我只有在想打電話時才會遇到問題localhost:8080/users。這似乎總是呼叫localhost:3000/users,顯然不會回傳正確的資料。在 react 應用程式的 package.json 檔案中,我定義了代理以在其上使用 express 服務器,localhost:8080并且它對我所有其他 API 呼叫都能正常作業,所以我很困惑為什么這個不能作業。
包.json:
"proxy": "http://localhost:8080",
該路由localhost:8080/users在直接呼叫 API 的瀏覽器中運行良好,并且是回傳資料的有效路由。

我使用所有相同的代碼來檢索資料,為什么我得到如此不同的結果?這讓我很困惑,所以感謝您的幫助謝謝:)
uj5u.com熱心網友回復:
您的問題似乎在您的getAllUsers函式中的這一行:
setUsers(records.shows);
從您所展示的內容來看,其資料/users具有屬性,而不是,因此該行應該是usersshows
setUsers(records.users);
似乎您在復制/粘貼時忘記更改此部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/534603.html
