React Native TypeError: 使用fetch()时网络请求失败

3

我正在使用React Native开发Android应用程序。使用此fetch请求时,我遇到了错误TypeError:network request failed

fetch('https://pixabay.com/api/?key=MY_KEY&q='+ this.props.jsondata.city.name +'&lang=en&image_type=photo&orientation=horizontal&category=travel&safesearch=true')
        .then(response => {
            console.dir(response);
            if (!response.ok) {
                throw Error(data.statusText);
            }
            return response.json();
        })
        .then(json => {
            console.log(json.hits[0].largeImageURL)
            this.setState(() => {
                return {backImage: json.hits[0].largeImageURL};
            });
        })
        .catch(err => {
            console.log('Unable to search image! ' + err);
        });

我已经在网上搜索过,但这个问题只在本地主机地址或http地址中出现,而不是我的情况。请求在componentDidMount()函数内部。我在应用程序的另一个位置做了一个类似的请求(具有相同的结构),但那里没有错误。我正在使用真实的android设备测试具有android原生代码编译的react-native应用程序。

5个回答

1
  1. AndroidManifest.xml 中添加 android:usesCleartextTraffic="true"

  2. 从你的 Android 文件夹中删除所有调试文件夹。


浪费了1-2个小时后,终于这个解决方案有用了!! - Shesh Narayan Deshmukh

0

我也遇到了同样的问题。

一般来说,当你的网络不安全时(例如,如果你使用的是 http 连接而不是 https),就会出现这个错误。

如果你查看官方文档,你会发现下面的警告。

在 Android 上,从 API 级别 28 开始,默认情况下也会阻止明文流量。可以通过在应用程序清单文件中设置 android:usesCleartextTraffic 来覆盖此行为。

因此,你可以尝试在 AndroidManifest.xml 文件的应用程序声明中添加 android:usesCleartextTraffic="true",通常位于 android/app/src/main/AndroidManifest.xml

如果这在我的情况下不起作用,你可以检查你的清单中是否有一个 android:networkSecurityConfig 声明。如果有,转到文件的位置(在我的情况下是 "@xml/network_security_config")并添加你想要信任的自定义域名。 以下是一个示例:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
        <domain includeSubdomains="true">localhost</domain>
        <!-- add your domain like below -->
        <domain includeSubdomains="true">192.168.8.103</domain>
        <domain includeSubdomains="true">pixabay.com</domain>
    </domain-config>
</network-security-config>

0
我猜错误的主要原因是模拟器SSL证书问题。 为了解决这个问题,您可以使用真实设备来测试应用程序,或者您可以设置一个持久的证书颁发机构(CA)。

0

所有这些解决方案都不起作用,因为到处都是提到“localhost”,而我并没有使用。我找到了一个适合我的解决方案,需要在以下文件中添加所需的主机: android/app/src/debug/res/xml/react_native_config.xml。 这是我的xml现在的样子:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
    <domain includeSubdomains="true">facebook.github.io</domain>
  </domain-config>
</network-security-config>

之后我的下面的获取请求开始工作:

fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
    Alert.alert(JSON.stringify(responseJson));
});
.catch((error) => {
    console.error(error);
});

是的,但有一件事:您正在调用HTTP而不是HTTPS端点。 - Stefan Majiros

-1

在进行http请求之前,您可以尝试验证设备是否具有互联网连接。React Native有一个模块可以验证:Netinfo

import { NetInfo } from 'react-native';

             ... your component code

checkInternetConnection = () => {

    return NetInfo.isConnected.fetch().then((isConnected) => {
        return isConnected;
      });

  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接