Could not connect to React Native development server on Android

前端 未结 28 2069
鱼传尺愫
鱼传尺愫 2020-11-30 22:10

When I run react-native run-android, it gives me the following error:

Could not connect to development server

28条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 22:37

    This is applicable to Android 9.0+ according to the Network Security Configuration. Well, so after trying all possible solutions I found on the web, I decided to investigate the native Android logcat manually. Even after adding android:usesCleartextTraffic="true", I found this in the logcat:

    06-25 02:32:34.561 32001 32001 E unknown:ReactNative: Caused by: java.net.UnknownServiceException: CLEARTEXT communication to 192.168.29.96 not permitted by network security policy
    

    So, I tried to inspect my react-native app's source. I found that in debug variant, there is already a network-security-config which is defined by react-native guys, that conflicts with the main variant.

    There's an easy solution to this. Go to /android/app/src/debug/res/xml/react_native_config.xml Add a new line with your own IP address in the like:

    
    
      
        localhost
        10.0.2.2
        10.0.3.2
        ***192.168.29.96***
      
    
    

    As my computer's local IP (check from ifconfig for linux) is 192.168.29.96, I added the above line in ***

    Then, you need to clean and rebuild for Android!

    cd /android
    ./gradlew clean
    cd 
    react-native run-android
    

    I hope this works for you.

提交回复
热议问题