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()
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"/>
I am getting this error as well with Android in React Native. It works fine with iOS.
I am also getting this error with Android in React Native.
Is axios really not supported in Android? 😨
Same issue, does anyone solve it?
will work in iOS but will not work in Android. HTTPS doesn't support in android.
mark
can any one help https://stackoverflow.com/questions/46307932/network-error-in-axios-post-request-react-native please ?
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
GET is not able to use body
.
I think you should remove your data
when using GET.
axios.interceptors.request.use((config) => {
if (config.method !== 'get') {
config.data = qs.stringify(config.data) // fix Rails i18n error
}
if (typeof config.params === 'undefined') {
config.params = {}
}
return AppSettingService.getAppSetting()
.then((appSetting) => {
config.params.locale = appSetting.locale
config.params.currency = appSetting.currency
return ProfileService.getCurrentUser()
.then((currentUser) => {
if (currentUser) {
config.headers.common.Authorization = currentUser.token
}
return config
})
})
})
I hava similar issues, but I fixed this Network Error with omiting data
when using GET.
@hzburki I had got the same issue as you, but I found that, on android emulator, the timeout for a network request seems to be 2 or 3 minutes. However, setting default timeout of Axios does not work on android emulator.
Hey @hpb0412 ... I'm sorry its been a while since I posted this so I don't remember how I got past the issue. However looking at it now it seems I hadn't enabled App Transport Security for iPhone at the time, since it was working fine on Android. But this doesn't help you.
It would help looking at the error log at backend where you're sending the GET request and trying the same request with Postman to make sure there is nothing wrong at the back-end code.
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
I am getting the same network error with a simple Get request
`var instance = axios.create({
baseURL: getEnvVars.apiHost,
timeout: 5000,
headers: {'x-api-key': getEnvVars.apiKey}
});
return instance.get('/products?brand=' + params.brand)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});`
`▼Network Error
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
or https://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.
please help with this, it still doesn't work, I'm having the same problem
@hsunami10 What is your domain? Do you have a repo with your app?
@hsunami10 I worked around the issue by setting up an external staging server and pointing to that for testing with the emulator.
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.
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.
With case upload media process, i suggest all of you to use rn-fetch-blob
instead.
@VitaliiK91 do you mean the ADB settings in Genymotion. Where is localhost setting to replace?
I'm having the same problem with a simple GET request to my Rest API hosted in heroku. On IOS emulator the same request works well.
axios.get('https://my-app-api.herokuapp.com/api')
.then(response => {
this.setState({ bets: response.data })
});
I tried to use headers too, but not working too.
axios.get('https://my-app-api.herokuapp.com/api',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
},
})
.then(response => {
this.setState({ bets: response.data })
});
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.
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 finally manage to fix the issue. Used my networks IP address and it works. eg http://
If you are trying to call localhost on android simulator created with AVD, replacing
localhost
with10.0.2.2
solved the issue for me.
Got them
this worked for me. I am using MAC
https://stackoverflow.com/a/53617769/5708097
similar issue here, everything works find with iOS, android just can't work!
i compared all the request config between iOS and android, exactly the same!
android always return a login page to me, even when i had hardcoded the cookie header.
Same issue here. I am already using 10.0.02
, and my actual call happened (it send an email), but respond an error (??).
.post(`/sendMail`, null, {
params: {
mail,
},
})
.then(response => response) // No output
.catch(error => {
console.log(error); // ERROR : Network Error
return error.response; // undefined
});
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.
(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
I came to this issue as I was experiencing exactly the same symptoms. So this might might be useful information to someone. I'm new to using the Android Emulator, so I was surprised the request, which was working for iOS would fail on Android's Emulator. It turns out that my server, which is https, not self signed had an issue and required a re-install and was therefore not correctly SSL handshaking, which meant I was also getting the same Network Error posted at the start of this post.
I would suggest 100% confirming the cert is installed correctly, getting a report for example from sslshopper - Hope this may help someone 👍
the same issue, it works well in ios,but get
If you are trying to call localhost on android simulator created with AVD, replacing
localhost
with10.0.2.2
solved the issue for me.
modified local hosts file ?
My GET request using Cordova comes back with Error: Network error
on Android, but works fine in a browser and on iOS emulator and iOS physical device. My GET request is:
this.axios.get('http://jsonplaceholder.typicode.com/posts/')
.then(function(response) {
self.tomData = response
})
.catch(function(error) {
self.error = true
self.errorText = error
})
And I'm using Cordova 8.0.0. I've tried HTTPS & HTTP, I've tried different domains as well.
What worked for me was instead of using https:// I used http:// for the Android emulator. For iOS http:// doesnt work while https:// does.
What worked for me was instead of using https:// I used http:// for the Android emulator. For iOS http:// doesnt work while https:// does.
This is not the solution if i have oonly one https domain.
That worked for me.
My header:
headers: {
'Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8'
}
I have a test application that its backend is done in Adonis (local) and the front react-native and axios, to show a get of an API, but in the emulated it presents the following error:
Possible Unhandled Promise Rejection (id: 0):
Error: Network Error
Error: Network Error ...,
in the insonima it works normally with methods GET, POST, DELETE ...
someone could help.
```import React, { Component } from 'react';
import {
Button
} from 'react-native';
import Axios from 'axios'
class App extends Component {
handleShowDB = async () => {
const DB = await Axios.get('http://127.0.0.1:3333/users/getuser/1')
console.log(DB)
}
render() {
return (
title={'Preenter code heress'}
onPress={() => this.handleShowDB()}
/>
)
}
};
export default App;
```
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/
That worked for me.
- 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' }
OMG, you've saved my time bro!
Nothing worked.
Is there any solution for this ?
What is the error?
Hello @helloitsm3, Just fixed this. Was experiencing same error as this issue title.
But fixed it replacing localhost
with 10.0.2.2
and making sure that data is on in android simulator.
If you are trying to call localhost on android simulator created with AVD, replacing
localhost
with10.0.2.2
solved the issue for me.
I'm so disappointed when it worked.
For anyone facing issues on Android 9, just add android:usesCleartextTraffic="true"
to application
tag in your AndroidManifest.xml
.
I read through all the answers above and just adding what worked for me.
@yasirlateef http
request is disabled by default on Android 9 or higher
this flag android:usesCleartextTraffic="true"
enable http
https://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic
is there anything to do on axios' end?
is there anything to do on axios' end?
There's nothing to do on Axios end. All you have to do is to use the ip address instead of localhost and it'll work
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
This could be the problem
Looks like the problem is related to some Android settings. If there is anything axios should have to improve, feel free to open an issue.
@ghost Super correct, 200% Right
http://192.168.43.49:3000/user/
Meu caso funcionou trocando o localhost pelo ip da maquina na chamada da api
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.
- change from localhost to your ip
- add http://
http://192.168.43.49:3000/user/
and :
keep Device(or emulator) and your system on the same network
If you have the luxury of stepping up to a newer Android version I've done the following tests:
Emulator Api24 does not work
Emulator Api25 does not work
Emulator Api26 works!
I haven't tried newer versions (exept on a physical phone (Android 10)) where it also works.
@ghost
I have removed it and include an image field as param by assign image.uri to value of param then it works.
Could you please let me know how to do this in detail?
Exactly same issue for me.
Most helpful comment
If you are trying to call localhost on android simulator created with AVD, replacing
localhost
with10.0.2.2
solved the issue for me.