facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
119.09k stars 24.32k forks source link

Fetch requests only work in debug mode when network inspector is enabled #37217

Closed egemenuzunali closed 1 year ago

egemenuzunali commented 1 year ago

Description

I am using react native together with Apollo Client and on ios everything works fine. For Android I have the following issue:

The Apollo client only connects to the server when debug mode is enabled and network requests are inspected via react native debugger. The fetch api also only works in debug mode and I believe this is the problem since the apollo client is also using fetch. I also have this issue when using a brand new react native init on android.

I have tried the following:

Same problem on both windows & MAC, has anyone come across this issue lately?

React Native Version

0.71.1

Output of npx react-native info

System: OS: macOS 13.3.1 CPU: (10) arm64 Apple M1 Max Memory: 81.89 MB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node Yarn: 1.22.19 - ~/.nvm/versions/node/v16.16.0/bin/yarn npm: 8.5.0 - ~/.nvm/versions/node/v16.16.0/bin/npm Watchman: 2023.02.27.00 - /opt/homebrew/bin/watchman Managers: CocoaPods: 1.12.0 - /opt/homebrew/bin/pod SDKs: iOS SDK: Platforms: DriverKit 22.2, iOS 16.2, macOS 13.1, tvOS 16.1, watchOS 9.1 Android SDK: Not Found IDEs: Android Studio: 2022.1 AI-221.6008.13.2211.9477386 Xcode: 14.2/14C18 - /usr/bin/xcodebuild Languages: Java: 11.0.16 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 18.2.0 => 18.2.0 react-native: 0.71.1 => 0.71.1 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found

Steps to reproduce

Snack, code example, screenshot, or link to a repository

    const getMovies = async () => {
        try {
            console.log('getting Movies');
            const response = await fetch('https://reactnative.dev/movies.json');
            const json = await response.json();
            console.log(json);
        } catch (error) {
            console.error(error);
        }
    };
github-actions[bot] commented 1 year ago
:warning: Newer Version of React Native is Available!
:information_source: You are on a supported minor version, but it looks like there's a newer patch available. Please upgrade to the highest patch for your minor or latest and verify if the issue persists (alternatively, create a new project and repro the issue in it). If it does not repro, please let us know so we can close out this issue. This helps us ensure we are looking at issues that still exist in the most recent releases.
cortinico commented 1 year ago

I also have this issue when using a brand new react native init on android

What is the issue? Do you have an error message or a status code to share?

egemenuzunali commented 1 year ago

I never got an error, the requests were never getting completed. Upgrading to the latest version actually fixed the fetch problem but the apollo issue still exists. Will investigate further but closing this issue

SaimNasser commented 1 year ago

Facing same issue. "react": "18.2.0", "react-native": "0.71.6",

AFoaad commented 1 year ago

having the same issue,

I get this error when I disable the network inspect { "message": "Network Error", "name": "Error", "stack": "createError@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:124428:26\nhandleError@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:124355:27\ndispatchEvent@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:27789:31\nsetReadyState@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:27079:33\n__didCompleteResponse@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:26915:29\nemit@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:1872:42\n__callFunction@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:2717:36\nhttp://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:2486:31\n__guard@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:2676:15\ncallFunctionReturnFlushedQueue@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.qiyas&modulesOnly=false&runModule=true:2485:21\ncallFunctionReturnFlushedQueue@[native code]", "config": { "url": "https://xxxxx", the endpoint is correct "method": "get", "headers": { "Accept": "application/json, text/plain, */*", }, "transformRequest": [null], "transformResponse": [null], "timeout": 30000, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "maxBodyLength": -1, "cancelToken": { "promise": { "_x": 1, "_y": 0, "_z": null, "_A": { "onRejected": null, "promise": { "_x": 0, "_y": 0, "_z": null, "_A": null } } } }, "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false } } }

System: OS: macOS 13.4 CPU: (10) x64 Apple M1 Pro Memory: 8.42 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 14.19.0 - /usr/local/bin/node Yarn: 1.22.15 - /usr/local/bin/yarn npm: 6.14.16 - /usr/local/bin/npm Watchman: Not Found Managers: CocoaPods: 1.11.3 - /opt/homebrew/bin/pod SDKs: iOS SDK: Platforms: DriverKit 22.2, iOS 16.2, macOS 13.1, tvOS 16.1, watchOS 9.1 Android SDK: Not Found IDEs: Android Studio: 2021.2 AI-212.5712.43.2112.8609683 Xcode: 14.2/14C18 - /usr/bin/xcodebuild Languages: Java: 17.0.7 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: ^16.13.1 => 16.14.0 react-native: ^0.64.0 => 0.64.4

hamzaali98 commented 1 year ago

@SaimNasser Heyy. I am stuck on a similar problem. Did you find a solution to this? "react": "17.0.1", "react-native": "0.64.4",

I am fetching a stream of data using react-native-fetch-api. It works with the debugger when network inspect is enabled but not without it

SaimNasser commented 1 year ago

@hamzaali98 Hello Hamza, yes i did resolve it. The problem i was facing was that no api calls were being made (with debugger) on android to our backend due to some security configurations of our dev server.

Create 'CustomClientFactory.java' file in android/app/src/java

package <your bundle id //com.app >;
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 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 CustomClientFactory implements OkHttpClientFactory {

    @Override
    public OkHttpClient createNewNetworkModuleClient() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

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

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

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(0, TimeUnit.MILLISECONDS)
                .readTimeout(0, TimeUnit.MILLISECONDS)
                .writeTimeout(0, TimeUnit.MILLISECONDS)
                .cookieJar(new ReactCookieJarContainer())
                .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                .hostnameVerifier((hostname, session) -> true); // Bypass hostname verification

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

Then in MainActivity.java import CustomClientFactory

import <your bundle id //com.app >.CustomClientFactory; 

Then in onCreate function of MainActivity.java add the following line

 OkHttpClientProvider.setOkHttpClientFactory(new CustomClientFactory());
hamzaali98 commented 1 year ago

@SaimNasser Thank you but i am facing a different issue. I am expecting a stream of data from an HTTP request. It works fine in debugging mode but I don't get the data when debugger is off. I found out that when remote debugging is enabled the code does not run on the phone but in the V8 engine of your chrome browser/react native debugger. When the remote debugging is disabled, code runs on the phone and some other engine which is probably causing the issue

SaimNasser commented 1 year ago

@SaimNasser Thank you but i am facing a different issue. I am expecting a stream of data from an HTTP request. It works fine in debugging mode but I don't get the data when debugger is off. I found out that when remote debugging is enabled the code does not run on the phone but in the V8 engine of your chrome browser/react native debugger. When the remote debugging is disabled, code runs on the phone and some other engine which is probably causing the issue

Thats the same issue i was facing. Api calls were only working when react native debugger was connected. I resolved it using that CustomClientFactory.