ann*_*ann 4 django android react-native fetch-api expo
我在我的 android 设备上使用 expo 客户端并设置了一个 django 服务器,localhost:8000我正在尝试在 react native 中使用 fetch 访问和端点。我看过如何从我的 Android 设备访问我的本地主机? 你如何在Android模拟器中连接本地主机?以及如何从 Eclipse 中的 Android Emulator 连接到我的 http://localhost Web 服务器,但这不起作用。
我也尝试使用我机器的 ip 地址而不是 localhost,但没有结果。这是一个示例代码
componentDidMount(){
return fetch('http://my-ip-address:8000/restapi/')
.then((response) => {
console.log("success")
response = response.json()
}).catch(error => {
console.error(error)
})
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
这可能是 django 配置的问题。特别是如果您手机的网络浏览器也无法获得预期的响应。
来自Django 文档:
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).
Run Code Online (Sandbox Code Playgroud)
请参阅如何从外部访问本地 Django 网络服务器,尽管答案也适用于本地网络:
python manage.py runserver 0.0.0.0:8000
0.0.0.0如果您知道机器的地址,您可以替换它。
在您的响应处理程序中还值得注意的是,它response.json()返回一个 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);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6689 次 |
| 最近记录: |