How to ignore SSL issues in axios using React Native?
Asked Answered
N

1

10

Hi I'm currently working with react native on Android with Expo. I am trying to send requests to my server which has a valid ssl certificate, but for some reason axios takes it as invalid, so axios does not allow me to send requests to my server's api.

this is the error i get:

Error: Network Error

So I wonder if there is any way to make axios ignore the problem with the ssl and can send the requests in a normal way

this is my code:

  try {
        const headers = {
            'Accept-Language': 'es-ES,es;q=0.8',
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
        };
        axios.get("https://URLtoMySERVER", {}, headers)
        .then(response => {
             console.log(response)
             const posts = response.data;
             console.log(posts)}
        ).catch(function(error) {
             console.log("error", error);
        });
 } catch (error) {
        console.log('err', error);
   }

some points that I want to clarify:

1- I can't use RNFetchBlob because I'm using Expo, and RNFetchBlob have some native libraries.

2- I can't use httpsAgent either with axios because apparently https library does not work with expo, or at least it does not work for me.

3- fetch doesn't work either

Is there any other alternative to axios or fetch that works in react native with expo and where you can ignore the problems of https?

Nocuous answered 17/1, 2020 at 7:14 Comment(7)
make sure your server is up and running.I have phase this type of error where my app is not connected with server for that my axios request return Error: Network ErrorCapillaceous
@Prakash Karena yes, I already made sure that my server works, with postman and insomnia the requests work wellNocuous
your server is in local or production ?Capillaceous
my server is in ProductionNocuous
Is there a solution for this? I'm getting the same error. Tks.Sanhedrin
@Nocuous did you find solution? Same issue i am also facing in my react-native axios code.Retinol
I had to change the ssl certificate, the letsencrypt certificate worksNocuous
E
0

if you are using React Native Cli you can easily bypass ssl for Android by the following method:

Add new file IgnoreSSLFactory.java to the same path of MainApplicaiton.java (/android/app/src/main/java/com/[yourapp]/

//IgnoreSSLFactory.java
package com.yourapp;  //Change to your app package name
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 java.util.concurrent.TimeUnit;
import android.util.Log;
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 IgnoreSSLFactory implements OkHttpClientFactory {
   private static final String TAG = "IgnoreSSLFactory";

   @Override
   public OkHttpClient createNewNetworkModuleClient() {
     try {
        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[]{};
                   }
                }
         };
         final SSLContext sslContext = SSLContext.getInstance("SSL");
         sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
         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);
    }
  }
}

Modify MainApplication.java

Add : import com.facebook.react.modules.network.OkHttpClientProvider;

Add : OkHttpClientProvider.setOkHttpClientFactory(new IgnoreSSLFactory()); into onCreate() function as below:

@Override  
public void onCreate() {    
   super.onCreate();    
   SoLoader.init(this, /* native exopackage */ false);    
   OkHttpClientProvider.setOkHttpClientFactory(new IgnoreSSLFactory());
   initializeFlipper(this,       
   getReactNativeHost().getReactInstanceManager());  
}
Eurypterid answered 20/7, 2024 at 6:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.