React native fetch api 不适用于本地主机、IP,甚至 10.0.2.2
React native fetch api does not work with localhost, IP, or even 10.0.2.2
我在我的 android 设备上使用 expo 客户端,并在 localhost:8000
上设置了一个 django 服务器,我正在尝试使用 react native 中的 fetch 访问和端点。我看过 How can I access my localhost from my Android device? How do you connect localhost in the Android emulator? and ,但没用。
我也尝试使用我机器的 ip 地址而不是 localhost,但没有结果。这是一个示例代码
componentDidMount(){
return fetch('http://my-ip-address:8000/restapi/')
.then((response) => {
console.log("success")
response = response.json()
}).catch(error => {
console.error(error)
})
}
我做错了什么?
解决方案
根据您的代码,
- 你的 django 端口:
:8080
- 您的提取目标端口:
:8000
再次检查。
我建议您在测试服务器 api 时使用 PostMan。
这可能是 django 配置的问题。特别是如果您的 phone 的网络浏览器也无法获得预期的响应。
来自Django docs:
Note that the default IP address, 127.0.0.1, is not accessible from other machines
on your network. To make your development server viewable to other machines on the
network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0 or :: (with IPv6 enabled).
参见 How to access the local Django webserver from outside world,尽管答案也适用于本地网络:
python manage.py runserver 0.0.0.0:8000
如果您知道,可以用机器地址替换0.0.0.0
。
还值得注意的是,在您的响应处理程序中 response.json()
returns 是 Promise,而不是 JSON。相反,你想要:
fetch('http://my-ip-address:8000/restapi/')
.then(response => response.json())
.then(responseJson => {
console.log("success");
console.log(responseJson);
})
.catch(error => {
console.error(error);
})
除了 csum 的回答之外,请检查防火墙是否允许 django 服务器远程访问您的 android 设备(设备 IP 为远程)。如果您安装了任何防病毒软件并控制防火墙,请确保其防火墙中有规则。
我在我的 android 设备上使用 expo 客户端,并在 localhost:8000
上设置了一个 django 服务器,我正在尝试使用 react native 中的 fetch 访问和端点。我看过 How can I access my localhost from my Android device? How do you connect localhost in the Android emulator? and ,但没用。
我也尝试使用我机器的 ip 地址而不是 localhost,但没有结果。这是一个示例代码
componentDidMount(){
return fetch('http://my-ip-address:8000/restapi/')
.then((response) => {
console.log("success")
response = response.json()
}).catch(error => {
console.error(error)
})
}
我做错了什么?
解决方案
根据您的代码,
- 你的 django 端口:
:8080
- 您的提取目标端口:
:8000
再次检查。 我建议您在测试服务器 api 时使用 PostMan。
这可能是 django 配置的问题。特别是如果您的 phone 的网络浏览器也无法获得预期的响应。
来自Django docs:
Note that the default IP address, 127.0.0.1, is not accessible from other machines
on your network. To make your development server viewable to other machines on the
network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0 or :: (with IPv6 enabled).
参见 How to access the local Django webserver from outside world,尽管答案也适用于本地网络:
python manage.py runserver 0.0.0.0:8000
如果您知道,可以用机器地址替换0.0.0.0
。
还值得注意的是,在您的响应处理程序中 response.json()
returns 是 Promise,而不是 JSON。相反,你想要:
fetch('http://my-ip-address:8000/restapi/')
.then(response => response.json())
.then(responseJson => {
console.log("success");
console.log(responseJson);
})
.catch(error => {
console.error(error);
})
除了 csum 的回答之外,请检查防火墙是否允许 django 服务器远程访问您的 android 设备(设备 IP 为远程)。如果您安装了任何防病毒软件并控制防火墙,请确保其防火墙中有规则。