axios: [React Native] AxiosError: Network Error on Android works fine on IOS

Describe the bug

On Andoid Axios request below is returning “AxiosError: Network Error”. All work fine on IOS.

The api call uses HTTPS.

I already tried:

  • Replace headers Content-Type with 'multipart/form-data' and application/json; charset=utf-8
  • Add data: {} to config These solutions doesn’t work.

API informations:

  • The backend works with NodeJS (Axios works well here)
  • The certificate on serverUrl:8339 is valid

Questions: Is adding a port related to this error?

Can you please explain to me what is wrong? Thank you in advance.

To Reproduce

No response

Code snippet

axios
      .get(
        `${serverUrl}:8339/api/users/user/check-username/username=${username}`,
        {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        },
      )

Expected behavior

{
    "available": true
}

Axios Version

Actual Github version 11/12/2022 (1.2.1)

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

v19.2.0

OS

Android

Additional Library Versions

React: 17.0.2
React Native: 0.68.2

Android: {
    API Level: 33,
    Version Name: Tiramisu
}

Additional context/Screenshots

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 7
  • Comments: 72

Most upvoted comments

Hi, we have the same problem, try changing Content-Type to content-type.

As @phil4lif mentioned above, Android does not allow http://localhost and therefore must be replaced with http://10.0.2.2. You can write a ternary in a useEffect that could look something like this:

import { Platform } from 'react-native';

useEffect(() => { const iosUrl = 'http://localhost:5000'; const androidUrl = 'http://10.0.2.2'; const url = Platform.OS === 'ios' ? iosUrl : androidUrl; (async () => { const response = await axios.get(url); ... })() }, [])

I recently encountered the same issue while uploading an image using Axios and FormData in my React Native project. The image wasn’t being uploaded to the server, and the error message was only “Network Error.” After some research, I discovered that setting the correct content-type header value and including the MIME type of the image being sent solved the problem.

Here’s a code snippet:

const formData = new FormData();
formData.append("image", {
  uri: imageUri,
  type: mime.getType(imageUri),
  name: imageUri.split("/").pop(),
});

const response = await axios.post(
  URL,
  formData,
  {
    headers: {
      "content-type": "multipart/form-data",
    },
  }
);

I used this mime package to get the MIME type I hope this information will help others who face the same issue.

I’m facing the same problem using Expo React Native on Android when trying to send formData (iOS works well). And like what @asapMaki discovered, it’s not axios’s problem since I’ve tried to replace axios with javascript’s fetch, and the problem is still there.

In the end, I found this life-saving post in Expo forum, which told me to add type: <mimeType> in the value of the formData, and it works!!! Hope that this can help someone with the same problem here.

const formData = new FormData();

formData.append("myImage", {
    uri: "myFileURI",
    name: "myfileName",
    type: "image/jpeg", // 🎉 Add this!!!!!!!
})

Note: I’m using this popular mime package to get the correct mimeType

If you use unencrypted (http only, i.e. to a server in the local network), then according to the React Native docs: On Android, as of API Level 28, clear text traffic is also blocked by default. This behaviour can be overridden by setting android:usesCleartextTraffic in the app manifest file.

If you are using Expo, install Expo BuildProperties with npx expo install expo-build-properties and add to app.json the following config:

{
  "expo": {
    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "usesCleartextTraffic": true
          }
        }
      ]
    ]
  }
}

Then rebuild your project with EAS. This works on Expo SDK 49.

i am having a reverse issue… android works but ios doesn’t

“react-native”: “0.71.3” “axios”: “^1.3.5”

@wHat0 I’m using axios 1.3.4 and the problem persists

There are different situations then

1- You should check your AndroidManifest.xml and add the below permissions after <manifest …/> tag if they are not there you should know that the permission are case sensitive. < uses-permission android:name=“android.permission.INTERNET” /> < uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” />

2- If you have permissions there and still got error then you should add android:usesCleartextTraffic=“true” to application tag in your AndroidManifest.xml .

http request is disabled by default on Android 9 or higher this flag android:usesCleartextTraffic=“true” enable http

3- If you’re using url like http://localhost… then replacing localhost with 10.0.2.2 and making sure that data is on in android simulator.

4- SomeTimes it worked like that.

Turn off the PC Wifi Close the emulator and wipe data. Start the emulator Turn on then PC Wifi My header:

headers: { 'Accept: ‘application/json’, ‘Content-Type’: ‘application/json; charset=utf-8’ }

Note : you should try for the GET request first if you are getting data and just unable to POST then you are making issue in your request it can be your header

like for form-data the Content type should be mentioned in headers as headers:{ “Content-Type” : “multipart/form-data”}

where as by default axios have “Content-Type” : “application/json”

Hi quick update, not sure what build you refer to, but I did try every method there is, from cleaning node module, going back to previous commits to see if it works. Nothing helped. At the end the problem wasn’t with axios, neither fetch was retrieving data on android. Problem was with the api and ssl certificates, handshake wasn’t happening, check with your backend team to try to debug. After that was resolved it was good on android. Lost a couple of hours trying to debug but glad it is over, hope it helps someone.

cuanto con el mismo error pero yo estoy utilizando la libreria de expo image picker y ya intente las respuestas anteriores y no me funcionaron nota estoy utilizando el sdk 47 y no da en expo go android solo da en expo web

este es mi codigo de formData const formData = new FormData()

formData.append('files',sendFile)
formData.append('FileName', nameImage)
formData.append('FolderName', 'Comprobantes')

await postUploadImage(formData);

I was having the opposite error, on Android it worked fine and on iOS it didn’t work only GET requests.

This started after upgrading to any version above 0.19.2.

The SOLUTION in my case was to use the request data as undefined instead of null for GET requests.

Example:

const response = await axios({
         url,
         params,
         method,
         data, <- For GET requests it must be undefined instead of null !!!
         baseURL,
         headers,
         ...config,
       });

if you are trying to make requests to http://localhost:3000 using Axios

use http://10.0.2.2:3000

instead of http://localhost:3000

Reference: https://stackoverflow.com/questions/49370747/network-error-with-axios-and-react-native

Not working in these versions now

"axios": "^1.4.0", "react": "18.1.0", "react-native": "0.70.1",

@wHat0 I’m using axios 1.3.4 and the problem persists

There is an issue with axios version 1.2.0 kindly use the latest version or go for axios@1.2.0-alpha.1 it will solve your problem.

just do

npm i axios@1.2.0-alpha.1

If you are trying it on your local, please check if the call is being made to the correct ip.

When using android emulator it makes call to a different ip. So you have to map your local port to your mobile port. This can be done using adb reverse tcp:[3000] tcp:[3000]

Once this is executed any emulator calls will be mapped to locals port and from there it will reach the right ip.

我相反,work fine on android, ios network error. “react”: “18.2.0”, “react-native”: “0.72.4”, “axios”: “^1.5.0”,

@wHat0 I’m using axios 1.3.4 and the problem persists

There are different situations then

1- You should check your AndroidManifest.xml and add the below permissions after <manifest …/> tag if they are not there you should know that the permission are case sensitive. < uses-permission android:name=“android.permission.INTERNET” /> < uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” />

2- If you have permissions there and still got error then you should add android:usesCleartextTraffic=“true” to application tag in your AndroidManifest.xml .

http request is disabled by default on Android 9 or higher this flag android:usesCleartextTraffic=“true” enable http

3- If you’re using url like http://localhost… then replacing localhost with 10.0.2.2 and making sure that data is on in android simulator.

4- SomeTimes it worked like that.

Turn off the PC Wifi Close the emulator and wipe data. Start the emulator Turn on then PC Wifi My header:

headers: { 'Accept: ‘application/json’, ‘Content-Type’: ‘application/json; charset=utf-8’ }

Note : you should try for the GET request first if you are getting data and just unable to POST then you are making issue in your request it can be your header

like for form-data the Content type should be mentioned in headers as headers:{ “Content-Type” : “multipart/form-data”}

where as by default axios have “Content-Type” : “application/json”

Worked for me Thanks!

I was at least a work day trying to solve this problem, in the end, what worked for me was @wHat0 solution step 4, hope you can solve it too guys !

in my case, the source of the problem was invalid ssl certificate. you can use react-native-blob-util package and determine the problem if the problem is releated with invalid ssl.

don’t forget to add trusty parameter image.

if you don’t want to use this package, you need to do ssl pinning etc. methods.

Axios returns network error, a better explanation would be great I guess.

headers: { “content-type”: “multipart/form-data”, },

This worked for us! "react-native": "0.70.8", "axios": "^1.3.5",

@spritrl Is your ${serverUrl} variable being imported from ‘react-native-config’ by any chance?
I am encountering a similar issue where the request works fine in ios simulator but doesn’t seem to even get to the backend in android emulator. I just tried logging my variable that I import from ‘react-native-config’ and it is undefined in android and is correct in ios.

import Config from 'react-native-config';
import { base, authBase } from './baseService';

const { API_VERSON } = Config;
console.log(API_VERSION);

EDIT: Hardcoding my api version did not fix, I’m still receiving a network error, and I’m running the backend locally and nothing happens in that terminal when I try to make the request, but it does still work correctly on ios.

SECOND EDIT: The app I’m working on is live and working in production on both ios and android.

THIRD AND FINAL EDIT: I found this old closed issue https://github.com/axios/axios/issues/973 the solution for me was https://github.com/axios/axios/issues/973#issuecomment-437221047 Vitaliik91’s comment: “If you are trying to call localhost on android simulator created with AVD, replacing localhost with 10.0.2.2 solved the issue for me.”

Any update here, We are also getting the same

I’m facing the same problem using Expo React Native on Android when trying to send formData (iOS works well). And like what @asapMaki discovered, it’s not axios’s problem since I’ve tried to replace axios with javascript’s fetch, and the problem is still there.

In the end, I found this life-saving post in Expo forum, which told me to add type: <mimeType> in the value of the formData, and it works!!! Hope that this can help someone with the same problem here.

const formData = new FormData();

formData.append("myImage", {
    uri: "myFileURI",
    name: "myfileName",
    type: "image/jpeg", // 🎉 Add this!!!!!!!
})

Note: I’m using this popular mime package to get the correct mimeType

I can confirm that adding ‘type’: <mimeType> solved the issue on my project

I solved this issue by adding Content-Type:'application/json'. Nothing to do with iOS/Android or Axios.

axios.create({
    baseURL: API_URL,
    headers: {
      Authorization: authToken,
      "Content-Type": "application/json",
    },
  });

Solved as follows, I was reporting axio.post(‘URL’, formdata, config) but in the config it was not informing headers:{}, ficou assim:

const config = { headers: { “content-type”: “multipart/form-data”, }, }

I encountered same error on android api level 33 emulator while trying to uploading pdf file, IOS simulator was OK. I changed type: 'pdf' to type: 'application/pdf'. Worked both on simulator and emulator

form.append('document', 
{ ...,
  type: 'application/pdf', // was 'pdf' before
  ...,
}

Guys for me what is worked : I tried downgrade I updated android files, disabled some codes etc. I was also using content-type as multipart/form-data But my mistake was. : I had an config object and I was updating/adding new keys to that object . Like config.headers.contentType=multipart/form-data
For android that did not worked. I set it with lower-case : config.headers[‘content-type’]=multipart/form-data

if (Platform.OS == "android") config.headers["content-type"] = "multipart/form-data"; else config.headers.contentType = "multipart/form-data";

@wHat0 thanks for the detailed steps but in my case I’m not using FormData, I’m sending a blob to aws s3 using a presigned (https) url