如何解决 React Native 中的“TypeError:网络请求失败"? [英] How to solve 'TypeError: Network request failed' in React Native?
问题描述
环境
我正在使用 React Native 和 Expo 开发一个移动应用程序.
I'm developing a mobile app with React Native and Expo.
另外,在我的本地环境中使用 Laravel 开发 api.(http://localhost:8000/)
Also, developing api with Laravel that is in my local environment. (http://localhost:8000/)
此应用正在 Expo 客户端应用上运行.
This app is working on Expo client app.
我要做什么
我想从 api 获取数据.
I wanna get datas from api.
代码
App.js
componentDidMount() {
return fetch('http://localhost:8000/api/test')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
错误
TypeError:网络请求失败
TypeError: Network request failed
世博版
3.22.3
如果您能给我任何建议,我将不胜感激.
I would appreciate it if you could give me any advice.
推荐答案
您的基本 URL 不应使用 http://localhost:8000
,请使用您的 IP 地址.
you should not use http://localhost:8000
for your base URL, please use your IP Address.
如果你使用Macbook,你可以在系统偏好设置中找到IP >网络
if you use Macbook, you can find the IP in System Preferences > Network
然后在你的 react native 应用中使用 fetch('http://172.20.10.5:8000/api/test')
.
then use fetch('http://172.20.10.5:8000/api/test')
in your react native app.
如果我通过浏览器访问时的基本 URL 是 http://172.20.10.5:8000/mysite/api/test
你需要在 react native fetch('http://172.20.10.5:8000/mysite/api/test')
if my base URL when access via browser is http://172.20.10.5:8000/mysite/api/test
you need fetch in react native fetch('http://172.20.10.5:8000/mysite/api/test')
基本上,android &ios 不允许使用 HTTP 请求,您需要执行以下操作以允许 HTTP 连接而不是 HTTPS.
basically, android & ios did not allow request using HTTP, you need to do something below to allow HTTP connection instead of HTTPS.
然后添加 android:usesCleartextTraffic="true";在你的 Android 清单 android/app/src/main/AndroidManifest.xml
and then add android:usesCleartextTraffic="true" in your Android manifest android/app/src/main/AndroidManifest.xml
在 info.plist 中添加这个
add this in info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
这篇关于如何解决 React Native 中的“TypeError:网络请求失败"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!