question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TypeError: Network request failed, only on Android using fetch()

See original GitHub issue

Description:

Only on Android I am getting TypeError: Network request failed using fetch() on an external API through http and https. It is not the SSL certificate since I checked the whole chain with SSL tools and that is all good.

I already tried: android:usesCleartextTraffic="true" in my android manifest. When I make an iOS build everything is working fine. I am making use of https://use-http.com/ which internally makes use of fetch(). But also when I use fetch() without the use-http library I am getting the same Network request failed error.

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (fetch.umd.js:473)
    at XMLHttpRequest.dispatchEvent (event-target-shim.js:818)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:574)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:388)
    at XMLHttpRequest.js:501
    at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
    at MessageQueue.__callFunction (MessageQueue.js:436)
    at MessageQueue.js:111
    at MessageQueue.__guard (MessageQueue.js:384)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:110)

React Native version:

info Fetching system and libraries information...
System:
    OS: Linux 4.18 Ubuntu 18.10 (Cosmic Cuttlefish)
    CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
    Memory: 258.36 MB / 15.40 GB
    Shell: 4.4.19 - /bin/bash
  Binaries:
    Node: 12.8.1 - /usr/local/bin/node
    npm: 6.11.3 - /usr/local/bin/npm
  SDKs:
    Android SDK:
      API Levels: 23, 26, 27, 28
      Build Tools: 26.0.2, 27.0.3, 28.0.3, 29.0.0, 29.0.2
      System Images: android-25 | Google Play Intel x86 Atom, android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom, android-29 | Google Play Intel x86 Atom
  IDEs:
    Android Studio: 3.5 AI-191.8026.42.35.5900203
  npmPackages:
    react: ~16.12.0 => 16.12.0 
    react-native: ~0.61.5 => 0.61.5 
  npmGlobalPackages:
    react-native-asset: 2.0.0
    react-native-cli: 2.0.1
    react-native-rename: 2.4.1
    react-native: 0.59.9

Example code:

    fetch(`${CONFIG.API_URL}/rest/rest/Mijn/Kenmerk`, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${token.accessToken}`,
        accept: 'application/json',
      }
    }).then(res => {
      console.log(res);
    }).catch(e => {
      console.log('ERROR', e); // throws error
    })

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:7

github_iconTop GitHub Comments

6reactions
cx5168commented, Sep 17, 2020

@cx5168 any solution for this ?

yes, i solved it.

my solutions: Create a class under android/app/src/main/java/XXXX. example: FetchApiClientFactory.java

package XXXX;

import com.facebook.react.modules.network.OkHttpClientFactory; import com.facebook.react.modules.network.OkHttpClientFactory; import com.facebook.react.modules.network.OkHttpClientProvider; import com.facebook.react.modules.network.ReactCookieJarContainer;

import java.security.cert.CertificateException; import java.util.ArrayList;

import java.util.List; import android.util.Log;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;

import okhttp3.CipherSuite; import okhttp3.ConnectionSpec; import okhttp3.OkHttpClient; import okhttp3.TlsVersion;

import static android.content.ContentValues.TAG;

public class FetchApiClientFactory implements OkHttpClientFactory { private static final String TAG = “OkHttpClientFactory”; @Override public OkHttpClient createNewNetworkModuleClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();



        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(0, TimeUnit.MILLISECONDS).readTimeout(0, TimeUnit.MILLISECONDS)
                .writeTimeout(0, TimeUnit.MILLISECONDS).cookieJar(new ReactCookieJarContainer());
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        throw new RuntimeException(e);
    }
}

}

Add the following code in MainApplication.java: @Override public void onCreate() { … OkHttpClientProvider.setOkHttpClientFactory(new FetchApiClientFactory()); //add the line }

good luck.

0reactions
fedefreicommented, Jan 30, 2021

Thanks @cx5168 . This workaround worked for me when switching from Azure to a local VPS provider.

Read more comments on GitHub >

github_iconTop Results From Across the Web

[Only Android] fetch Error : [Network request failed] #33217
fixed TypeError: Network request failed when upload file to http not https with Android debug builds ; Fetch not working on Android 9...
Read more >
React Native fetch() Network Request Failed - Stack Overflow
1) To find out the exact error in the logs, I first enabled 'Debug JS Remotely' using Cmd + M on the app...
Read more >
Improve "TypeError: Network request failed" error message
Network request failed, this error occurs usually when api call failed or you have some internet issue. In android emulator, sometimes this error...
Read more >
Fetch Error : [TypeError: Network request failed] : r/reactnative
When I want to make a request to an endpoint that I want, it throws me the error [TypeError: Network request failed], but...
Read more >
[typeerror: network request failed] - You.com | The AI Search ...
Since your Android device has an IP of its own, you need to point the URL to your computers IP address instead of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found