axios: Axios doesn't work with Android (emulator) raising a Network Error
I’n new with React Native, and I was playing around with components and http ajax request, and all went fine with iOs emulator, until I thought to test on Android emulator.
This is my Http class:
import 'url-search-params-polyfill';
import axios from 'axios';
import { AsyncStorage } from 'react-native';
import Rx from 'rxjs/Rx';
let _HttpServiceInstance = null;
class HttpService {
constructor(envStr) {
console.log('DEFAULT', axios.defaults);
if(!_HttpServiceInstance){
this.__proto__.ghtnk = null;
axios.defaults.baseURL = this.getBaseUrlApi()[envStr || 'DEV'];
axios.interceptors.response.use(
(resp) => {
let ghresp = resp.data || resp;
ghresp.status = resp.data ? resp.data.status : resp.status;
return ghresp;
},
(err) => {
if( err.status === 401 ){
this.removeToken();
// go to login
}
return Promise.reject(err);
}
)
_HttpServiceInstance = this;
}
return _HttpServiceInstance;
}
getBaseUrlApi = () => {
return {
DEV : 'https://dev-api.domainname.com/',
TEST: 'https://test-api.domainname.com/',
QA : 'https://qa-api.domainname.com/',
LIVE: 'https://api.domainname.com/',
};
}
switchBaseUrlApi(envStr) {
axios.defaults.baseURL = this.getBaseUrlApi()[envStr];
}
getToken = (callback) => {
let promise = AsyncStorage.getItem('ghtkn');
if( callback ){
promise.then(callback, () => { console.log('getToken: ', err) });
}
else return promise;
};
setToken = (token) => {
return AsyncStorage.setItem('ghtkn', token);
};
removeToken = () => {
AsyncStorage.removeItem('ghtkn');
};
setAuthHeaders = (callback, noNeedToken) => {
if ( noNeedToken ) {
callback(); return;
}
this.getToken(
(token) => {
if (token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
callback();
}
else{ console.log('NO TOKEN PRESENT'); }
},
(err) => { console.log('GET TOKEN: ', err); },
);
};
// GET
get = (url) => {
let subject = new Rx.Subject();
this.setAuthHeaders((token) => {
axios.get(url).then(
(data) => { subject.next(data); },
(err) => { console.log('GET: ', err); }
);
});
return subject;
};
// POST
post = (url, payload, noNeedToken) => {
let subject = new Rx.Subject();
this.setAuthHeaders(() => {
axios.post( url, this.setParams(payload)).then(
(resp) => { subject.next(resp); },
(err) => {
console.log('POST ERROR');
console.log(err.request, Object.keys(err) );
subject.error(err);
}
);
}, noNeedToken);
return subject;
};
// PUT
put = (url, payload) => {
let subject = new Rx.Subject();
this.setAuthHeaders((token) => {
axios.put( url, this.setParams(payload)).then(
(resp) => { subject.next(resp); },
(err) => { console.log('PUT: ', err); }
);
});
return subject;
};
// LOGIN
login = (user, pw) => {
return this.post('user/authentication', {username: user, password: pw}, true)
.do((resp) => { this.setToken(resp.token); })
};
setParams = (jsonParams) => {
let params = new URLSearchParams();
for(param in jsonParams){
if( jsonParams.hasOwnProperty(param) ){
params.append(param, jsonParams[param]);
}
}
return params;
};
}
export { HttpService };
This is the error I’m getting from the post request, using login() function I created using axios.post()
NOTE:
-
I’m using the latest version of Axios ^0.16.2
-
My AndroidManifest.xml contains:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
- The APIs are under VPN, as I wrote all works fine with iOs emulator but doesn’t with the Android one.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 32
- Comments: 58
If you are trying to call localhost on android simulator created with AVD, replacing
localhost
with10.0.2.2
solved the issue for me.will work in iOS but will not work in Android. HTTPS doesn’t support in android.
For anyone facing issues on Android 9, just add
android:usesCleartextTraffic="true"
toapplication
tag in yourAndroidManifest.xml
.I read through all the answers above and just adding what worked for me.
Guys, I also struggling on this issue for quit while. But I figured out the issue of my axios post network createError on Android device now. The reason to axios Network Error is because the form data I passed to axios contains wrong type of data object I guess. I have include an image object(ImagePicker object from Expo) as a one of param of form data which not accept by axios I think. Axios might only receive string, float, int or image as param. image cannot pass as param, it is not an type of image, it is an react native object, I have removed it and include an image field as param by assign image.uri to value of param then it works. Hope this will help some of people who may encounter same problem as I was facing before. Deleting some of your form data one by one when you are testing axios Network error, you will find out which one is the cause of issue.
@yasirlateef
http
request is disabled by default on Android 9 or higherthis flag
android:usesCleartextTraffic="true"
enable httphttps://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic
That worked for me.
My header:
Nothing worked. Is there any solution for this ?
OMG, you’ve saved my time bro!
Same issue here. I am already using
10.0.02
, and my actual call happened (it send an email), but respond an error (??).After searching, this issue seems to happen only when I am updating a table in my DB. The strangest thing is that my update actually happened as programmed. There is just… No response.
Got them
I finally manage to fix the issue. Used my networks IP address and it works. eg http://<Network IP emulator connects to>:<port where API is served>/api
More here
I had a similar problem and found a solution. My problem was related to my domain. I found that the domain must not have
_
in it. For exemple,https://my_api.mydomain.com
will not work. But,https://my-api.mydomain.com
orhttps://api.mydomain.com
will work. ~Note that my SSL certificate came from CloudFlare so this may be a SSL certificate problem too.~Edit: According to http://ssllabs.com, both certificates are identical and are supposed to work on all last Android version.
Is axios really not supported in Android? 😨
I had similar problem with my website hosted on AWS EC2 working fine in desktop browser, but it wasn’t fetching data from the database through the API (hosted also there). I was trying to fetch it through
http://localhost/api/...
and that worked fine on desktop, but for some reason it did not in any Android browser (tried on actual device, I don’t have Android Studio installed). It was giving me Network Error (I found out through logcat logs).Somebody here recommended to change localhost to the actual IP address of the server, even though that’s working fine on desktop, and so I tried changing the URL to
http://PUBLIC_IP_ADDRESS/api/...
and it worked! Altough, I’m not happy about this solution, it was the only way it worked. Hope this helps someone.http://192.168.43.49:3000/user/
I’m so disappointed when it worked.
Hello @helloitsm3, Just fixed this. Was experiencing same error as this issue title. But fixed it replacing
localhost
with10.0.2.2
and making sure that data is on in android simulator.At least for me, which I have api running locally by “Adonis”, I put the following address in my android emulator, which is different from the address used by the computer.
/* Endereços para cada emulador/simulador: ** Genymotion: http://10.0.3.2:3333/ ** Emulador Android Studio: http://10.0.2.2:3333/ ** Simulador IOS: http://localhost:3333/
https://blog.rocketseat.com.br/react-native-autenticacao/
What worked for me was instead of using https:// I used http:// for the Android emulator. For iOS http:// doesnt work while https:// does.
the same issue, it works well in ios,but get
modified local hosts file ?
(Sorry for the double post)
I just open a StackOverFlow topic where I tried to be more precise, there it is : https://stackoverflow.com/questions/54108848/network-error-with-axios-and-android-emulator
this worked for me. I am using MAC https://stackoverflow.com/a/53617769/5708097
I’m having the same issue as well. I’m on the latest version of Android and I’ve tried sending a simple text over to my server but still receiving network error. Same thing goes for the get request
I am also having the same problem. This is only related to Android 7.0, for other Android versions, it works well. Problem is that Axios https post request is not even reaching to the server. It got failed with Network Error only because of SSL Handshake got failed. It works well with all iOS versions as well as all Android versions except Android 7.0. Looks like Android 7.0 has some serious problem in okhttp.
it seem like a “fetch problem” i had met on React Native specific for Android 7.0. The reason for that is using self signed certificate
Same Issue under different conditions.
Axios throwing Network Error, but only on iOS Simulator.
Works Fine on android (Tested on actual Device). Using AWS server with http not https.
Help Please