我正在尝试使用React Native的fetch get请求从本地托管的Express API中获取JSON数据。
我们的React Native代码如下:
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被显示出来,所以我不知道出了什么问题。
localhost
指的是该设备的本地主机,而不是您计算机的本地主机,您需要将localhost更改为您计算机的本地IP。 - undefined