axios
axios copied to clipboard
[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'
andapplication/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
Hi, we have the same problem, try changing Content-Type
to content-type
.
Any update here, We are also getting the same
We had same issue before, but after downgrading to 0.19.1 it was fixed. today we are getting this error again with 0.19.1
Worked flawlessly so far. Started to happen to me last night. Version was 1.2.1, then tried to downgrade to 0.19.1. Also didn't work
import Axios, {AxiosError, AxiosRequestConfig} from 'axios';
export const AXIOS_INSTANCE = Axios.create({
baseURL: 'https...',
}); // use your own URL here or environment variable
export const customAxiosInstance = <T>(
config: AxiosRequestConfig,
): Promise<T> => {
const source = Axios.CancelToken.source();
const promise = AXIOS_INSTANCE({...config, cancelToken: source.token}).then(
({data}) => data,
);
// @ts-ignore
promise.cancel = () => {
source.cancel('Query was cancelled');
};
return promise;
};
Using it like this, with react query
const fetchNews = ({pageParam: page = 0}) =>
customAxiosInstance<{data: News[]}>({
url: `novosti`,
method: 'get',
params: {
size,
page,
},
});
@spritrl @asapMaki does this issue persist even after build? cause I was facing the same issue with emulator but not after the build still can't figure out why the issue exist on emulator.
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.
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
@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 Know solution to this issue, tried adjusting my code based on some comment above. none worked.
Am so so frustrated because this works perfectly on IOS.
I'm getting the same issue
Is there a known solution ? I have the same error
Same error ...
same error here
Has anyone have figured out any solution so far?
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.
getting same error
When I used const data = new FormData(); data.append("profile_pic", { uri: image.path, type: image.mime, name: image.path.split("/").pop(), });
instead of const data = new FormData(); data.append("profile_pic", { uri: image.sourceURL, type: image.mime, name: image.filename, });
problem is resolved.
What I found is that on iOS, images selected from the camera or photo library are saved in the local file system, and the source URL is used to reference the image in the React Native Image Picker library. On the other hand, on Android, images selected using the image picker are returned as base64 encoded data or a file URI, but not as a source URL. This difference in behavior is due to the underlying operating system and the native image picker libraries that React Native Image Picker depends on.
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);
There is an issue with axios version 1.2.0 kindly use the latest version or go for [email protected] it will solve your problem.
just do
npm i [email protected]
@wHat0 I'm using axios 1.3.4 and the problem persists
@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"
Always make a new build if you make any changes in AndroidManifest.xml
@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
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,
});
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 ofnull
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, });
What version of axios , used here ?!
headers: { "content-type": "multipart/form-data", },
This worked for us! "react-native": "0.70.8",
"axios": "^1.3.5",
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 ofnull
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, });
What version of axios , used here ?!
"react-native": "0.68.6"
"axios": "^1.3.4"
i am having a reverse issue... android works but ios doesn't
"react-native": "0.71.3" "axios": "^1.3.5"
any solution ?