Network Error when use axios in React Native

21,252

Solution 1

I think this is a problem with http and https request. SO to enable https request try the one below :

The easy way to implement this is to use this attribute to your AndroidManifest.xml where you allow all http for all requests:

android:usesCleartextTraffic="true"

Solution 2

try adding bellow code in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Solution 3

For Android, instead of using: localhost, use 10.0.2.2.

Share:
21,252
Andrew Terex
Author by

Andrew Terex

Updated on November 28, 2021

Comments

  • Andrew Terex
    Andrew Terex over 2 years

    This is long-standing problem for me and I can't find solution at all.

    Within my react native project(react-native-cli), I send request to server using axios package. But when I'm testing with my android phone, it gives [Error: Network Error]. With emulator, it's okay.

    I'm sure this is not back-end problem because I've tested with several servers. And I also used fetch instead but got same error.

    Here is version information.

    "axios": "^0.19.0",
    "react": "16.9.0",
    "react-native": "0.61.5",
    

    Sometimes, it's working on android phone too. This problem is biggest mystery and I suffered for a long time.

    Somebody who experienced this issue, please alive me. Thank you for careful reading.

    Sometimes, it's not working even with android emulator. But after deleted original emulator and created new emulator, it's working.

    const serverUrl = "https://server.com";
    axios.post(serverUrl + "/api/candidates/login", {
                "email": this.state.email ,
                "password": this.state.password
            }, {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then((response) => {
                    console.log(response.data);
            }).catch((error) => {
                    console.log(error);
            })
    
  • Andrew Terex
    Andrew Terex over 4 years
    I already added it to 'AndroidManifest.xml' in the application tag.
  • Gaurav Roy
    Gaurav Roy over 4 years
    after adding it to AndroidManifest did you do android:bundle and then build a new apk and tried with that?
  • Andrew Terex
    Andrew Terex over 4 years
    I'm testing on development server with my android phone.
  • William Bridge
    William Bridge over 3 years
    what will be the impact of adding this option in versions prior to android 9 ?