'React native TypeError: Network request failed with fetch()

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

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 componentDidMount() 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 compiled in android native code.



Solution 1:[1]

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

Solution 2:[2]

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

  2. Delete all debug folder from your android folder.

Solution 3:[3]

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).

Solution 4:[4]

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

Solution 5:[5]

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 component code

checkInternetConnection = () => {

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

  };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wilbur Dsouza
Solution 2 double-beep
Solution 3 Undo
Solution 4 Taur
Solution 5 Armando Monjane