最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React native TypeError: Network request failed with fetch() - Stack Overflow

programmeradmin6浏览0评论

I'm using React native for developing an android application. With this fetch request I'm getting the error TypeError: network request failed:

fetch('/?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);
        });

I've already searched online but this problem appears only with localhost addresses or http, that is not my case. The request is inside the ponentDidMount() function. I've made a similar request (with the same structure) in an another place of the application but there is no error there. I'm using a real android device to testing the app with the react-native app piled in android native code.

I'm using React native for developing an android application. With this fetch request I'm getting the error TypeError: network request failed:

fetch('https://pixabay./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);
        });

I've already searched online but this problem appears only with localhost addresses or http, that is not my case. The request is inside the ponentDidMount() function. I've made a similar request (with the same structure) in an another place of the application but there is no error there. I'm using a real android device to testing the app with the react-native app piled in android native code.

Share Improve this question edited Mar 17, 2022 at 10:16 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Sep 4, 2018 at 10:05 bertonc96bertonc96 8263 gold badges14 silver badges27 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 1
  1. Add android:usesCleartextTraffic="true" in AndroidManifest.xml.

  2. Delete all debug folder from your android folder.

None of these solutions worked since everywhere folks were referring to "localhost", which i was not using i found a solution that worked for me, for which you need to add the required host in the following file android/app/src/debug/res/xml/react_native_config.xml. This is my how my xml looks now:

<?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>

After which my below fetch request started working:

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);
});

I suppose the main reason for the error is emulator SSL certificate issue. To solve the issue you may use a real device for testing your app or you may set up a persistent Certificate Authority (CA).

I had the same problem.

In general, this error occurs when your network is not secure (for example, if you use an http connection instead of https).

If you check the official documentation, you will find the warning below.

On Android, as of API Level 28, clear text traffic is also blocked by default. This behaviour can be overridden by setting android:usesCleartextTraffic in the app manifest file.

So you can try adding android:usesCleartextTraffic="true" in the application declaration of your AndroidManifest.xml file usually located at android/app/src/main/AndroidManifest.xml.

If this doesn't work as in my case, you can check if there is an android:networkSecurityConfig declaration in your manifest. If there is, go to the location of the file ("@xml/network_security_config" in my case) and add your custom domain that you want to trust. Here is an example:

<?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.</domain>
    </domain-config>
</network-security-config>

You could try verifying if the device has internet connection before making the http request. React Native has a module to verify that: Netinfo.

import { NetInfo } from 'react-native';

             ... your ponent code

checkInternetConnection = () => {

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

  };
发布评论

评论列表(0)

  1. 暂无评论