[英]Connecting to localhost with React Native
我正在嘗試使用 react native fetch get 請求從本地托管的 express API 獲取 json。 我們的反應本機代碼是:
useEffect(() => {
fetch("http://localhost:5000/api/listings")
.then((response) => response.json())
.then((responseJSON) => {
console.log(responseJSON);
setIsLoading(false);
setListings(responseJSON);
})
.catch((error) => console.log(error));
}, []);
當我們嘗試發送請求時會記錄以下錯誤:
Network request failed
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:30140:19 in <unknown>
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31129:20 in <unknown>
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31045:8 in _callTimer
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:31253:8 in Object.callTimers
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:3213:30 in MessageQueue.__callFunction
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:2945:16 in <unknown>
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:3167:12 in MessageQueue.__guard
at http://192.168.1.34:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:2944:13 in MessageQueue.callFunctionReturnFlushedQueue
從 postman 發送 get 請求時,顯示 json 所以我很困惑出了什么問題。
我相信下面的代碼會對你有所幫助。 在終端/cmd 中輸入。 您的模擬器必須打開。
adb reverse tcp:5000 tcp:5000
現在您的鏈接應該可以工作http://localhost:5000/api/listings
如果第一個選項不起作用,請嘗試用以下鏈接替換您的鏈接:
http://10.0.2.2:5000/api/listings
這是因為 Android 不將 localhost 理解為您的 PC,因為它是 localhost,所以在第一選擇中,我們將模擬器門流量重定向為 Windows / ZEDC9F0A5A5D57797818E37364743。 在 MacOS 中不會發生此錯誤,因為 MacOS 知道整個環境是 localhost。
運行以下命令訪問 localhost 或 127.0.0.1 或您計算機的 ip
adb -s <device_name> reverse tcp:backend_port tcp:backend_port
例子:
adb -s emulator-5554 reverse tcp:8080tcp:8080
或者
adb reverse tcp:8080 tcp:8080
開發環境是一個上下文,android 運行器環境(如果是這個)是另一個上下文。
如果您的后端在節點中,則可以使用serve
lib 。 它是如此獨立,我認為這是最簡單的形式。
如果您使用的是 Linux(類似 Debian),您也可以在 /etc/hosts/ 文件中配置主機。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.