当我使用react-native init (RN版本0.29.1)创建一个全新的项目,并在渲染方法中获取公共facebook演示电影API时,它抛出了一个网络请求失败。有一个非常无用的堆栈跟踪,我不能调试网络请求在chrome控制台。这是我发送的fetch:
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
通过在0.0.0.0上运行模拟服务器
注意:当你使用json-server运行另一个服务器时,这在Expo上有效。
另一种方法是在0.0.0.0而不是localhost或127.0.0.1上运行模拟服务器。
这使得模拟服务器可以在LAN上访问,因为Expo要求开发机器和运行Expo应用程序的移动设备在同一个网络上,所以模拟服务器也可以访问。
在使用json-server时,可以使用以下命令实现这一点
Json-server——host 0.0.0.0——port 8000 ./db。json,看
请访问此链接了解更多信息。
对于android,在AndroidManifest.xml的应用程序标签中添加android:networkSecurityConfig="@xml/network_security_config",如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
</manifest>
Network_security_config.xml文件内容:
<?xml version='1.0' encoding='utf-8'?>
<network-security-config>
<debug-overrides>
<trust-anchors>
<!-- Trust user added CAs while debuggable only -->
<certificates src="user" />
</trust-anchors>
</debug-overrides>
<!-- let application to use http request -->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>