当我使用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);
});
Android用户:
Replace localhosts to a Lan IP addresses because when you run the project on an Android device, localhost is pointing to the Android device, instead of your computer, example: change http://localost to http://192.168.1.123
If your request URL is HTTPS and your Android device is under a proxy, assume you have installed User-added CA(like burp suite's CA or Charles's CA) in your Android device, make sure your Android version is below Nougat(7.0), because: Changes to Trusted Certificate Authorities in Android Nougat
User-added CAs
Protection of all application data is a key goal of the
Android application sandbox. Android Nougat changes how applications
interact with user- and admin-supplied CAs. By default, apps that
target API level 24 will—by design—not honor such CAs unless the app
explicitly opts in. This safe-by-default setting reduces application
attack surface and encourages consistent handling of network and
file-based application data.
对于Android设备,进入您的项目根文件夹并运行命令:
adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]
例如:adb reverse tcp:8088 tcp:8088
这将使您的物理设备(即。Android手机)监听本地主机服务器运行在您的开发机器(即您的计算机)地址http://localhost:[your_own_server_port]。
之后,你可以直接在react-native fetch()调用中使用http:localhost:[your_port] /your_api。
通过在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,看
请访问此链接了解更多信息。