Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Axios doesn't work with Android (emulator) raising a Network Error #973

Closed
Donovantxy opened this issue Jun 25, 2017 · 58 comments
Closed

Axios doesn't work with Android (emulator) raising a Network Error #973

Donovantxy opened this issue Jun 25, 2017 · 58 comments

Comments

@Donovantxy
Copy link

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()

screen shot 2017-06-24 at 22 32 54

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.
@brentmitchell25
Copy link

I am getting this error as well with Android in React Native. It works fine with iOS.

@farhaan
Copy link

farhaan commented Jul 11, 2017

I am also getting this error with Android in React Native.

@simplenotezy
Copy link

Is axios really not supported in Android? 😨

@rogerluo410
Copy link

Same issue, does anyone solve it?

@milon87
Copy link

milon87 commented Sep 16, 2017

will work in iOS but will not work in Android. HTTPS doesn't support in android.

@zhe-he
Copy link

zhe-he commented Sep 19, 2017

mark

@hashemirafsan
Copy link

@hzburki
Copy link

hzburki commented Oct 25, 2017

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

@miriyas
Copy link

miriyas commented Dec 20, 2017

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.

@hpb0412
Copy link

hpb0412 commented Jan 17, 2018

@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.

@hzburki
Copy link

hzburki commented Jan 17, 2018

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.

@Winglonelion
Copy link

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

@PaddyLock
Copy link

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

  • node_modules/axios/lib/core/createError.js:16:24 in createError
  • node_modules/axios/lib/adapters/xhr.js:87:25 in handleError
  • node_modules/raven-js/src/raven.js:377:26 in wrapped
  • node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
  • node_modules/react-native/Libraries/Network/XMLHttpRequest.js:567:29 in setReadyState
  • node_modules/react-native/Libraries/Network/XMLHttpRequest.js:397:25 in __didCompleteResponse
  • node_modules/react-native/Libraries/Network/XMLHttpRequest.js:503:16 in
  • node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:180:12 in emit
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:351:47 in __callFunction
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:116:26 in
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:314:6 in __guardSafe
  • node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:115:17 in callFunctionReturnFlushedQueue`

@alexandcote
Copy link

alexandcote commented Jun 27, 2018

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.

@hsunami10
Copy link

please help with this, it still doesn't work, I'm having the same problem

@alexandcote
Copy link

alexandcote commented Sep 18, 2018

@hsunami10 What is your domain? Do you have a repo with your app?

@PaddyLock
Copy link

@hsunami10 I worked around the issue by setting up an external staging server and pointing to that for testing with the emulator.

@ghost
Copy link

ghost commented Oct 9, 2018

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.

@VitaliiK91
Copy link

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.

@Winglonelion
Copy link

With case upload media process, i suggest all of you to use rn-fetch-blob instead.

@PaddyLock
Copy link

@VitaliiK91 do you mean the ADB settings in Genymotion. Where is localhost setting to replace?

@daibertdiego
Copy link

daibertdiego commented Nov 15, 2018

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 }) });

@daibertdiego
Copy link

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 }) });

@mahesh-vidhate
Copy link

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.

@helloitsm3
Copy link

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

@helloitsm3
Copy link

helloitsm3 commented Dec 3, 2018

I finally manage to fix the issue. Used my networks IP address and it works. eg http://:/api

More here

@RyuK-H
Copy link

RyuK-H commented Dec 4, 2018

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.

Got them

@rollrodrig
Copy link

this worked for me. I am using MAC
https://stackoverflow.com/a/53617769/5708097

@shuangyu
Copy link

shuangyu commented Jan 2, 2019

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.

@GuillaumeRZ
Copy link

GuillaumeRZ commented Jan 3, 2019

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.

@wuxiii
Copy link

wuxiii commented Mar 27, 2019

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 with 10.0.2.2 solved the issue for me.

modified local hosts file ?

@sts-ryan-holton
Copy link

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.

@0xamogh
Copy link

0xamogh commented May 16, 2019

What worked for me was instead of using https:// I used http:// for the Android emulator. For iOS http:// doesnt work while https:// does.

@Biplovkumar
Copy link

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.

@hugosbg
Copy link

hugosbg commented Jun 10, 2019

That worked for me.

  1. Turn off the PC Wifi
  2. Close the emulator and wipe data.
  3. Start the emulator
  4. Turn on then PC Wifi

My header:

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

@Andersonfrfilho
Copy link

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 {

  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 (
      <Button
        title={'Preenter code heress'}
        onPress={() => this.handleShowDB()}
      />
    )
  }
};
export default App;

https://ibb.co/7J5cJH9
`

@Andersonfrfilho
Copy link

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/

@fxbayuanggara
Copy link

That worked for me.

  1. Turn off the PC Wifi
  2. Close the emulator and wipe data.
  3. Start the emulator
  4. 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!

@Rupeshiya
Copy link

Nothing worked.
Is there any solution for this ?

@helloitsm3
Copy link

What is the error?

@Rupeshiya
Copy link

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.

@tayfunyasar
Copy link

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.

I'm so disappointed when it worked.

@yasirlateef
Copy link

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.

@ivanguimam
Copy link

@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

@yasuf
Copy link
Collaborator

yasuf commented Nov 5, 2019

is there anything to do on axios' end?

@helloitsm3
Copy link

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

@christian-hess-94
Copy link

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

@chinesedfan
Copy link
Collaborator

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.

@Olayinka-mumin
Copy link

@ghost Super correct, 200% Right

@KBiswas98
Copy link

  1. change from localhost to your ip
  2. add http://

http://192.168.43.49:3000/user/

@CLQueiroz
Copy link

Meu caso funcionou trocando o localhost pelo ip da maquina na chamada da api

@martin-lukas
Copy link

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.

@hamidone
Copy link

  1. change from localhost to your ip
  2. add http://

http://192.168.43.49:3000/user/

and :
keep Device(or emulator) and your system on the same network

@AndersDrevin
Copy link

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.

@bychung
Copy link

bychung commented May 14, 2020

@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.

@axios axios locked and limited conversation to collaborators May 22, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests