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 · 54 comments
Closed

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

Donovantxy opened this issue Jun 25, 2017 · 54 comments

Comments

@Donovantxy
Copy link

@Donovantxy Donovantxy commented Jun 25, 2017

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

This comment has been minimized.

Copy link

@brentmitchell25 brentmitchell25 commented Jul 11, 2017

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

@farhaan

This comment has been minimized.

Copy link

@farhaan farhaan commented Jul 11, 2017

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

@simplenotezy

This comment has been minimized.

Copy link

@simplenotezy simplenotezy commented Jul 27, 2017

Is axios really not supported in Android? 😨

@rogerluo410

This comment has been minimized.

Copy link

@rogerluo410 rogerluo410 commented Aug 4, 2017

Same issue, does anyone solve it?

@milon87

This comment has been minimized.

Copy link

@milon87 milon87 commented Sep 16, 2017

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

@zhe-he

This comment has been minimized.

Copy link

@zhe-he zhe-he commented Sep 19, 2017

mark

@hashemirafsan

This comment has been minimized.

@hzburki

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@Winglonelion Winglonelion commented May 5, 2018

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

This comment has been minimized.

Copy link

@PaddyLock PaddyLock commented Jun 6, 2018

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@hsunami10 hsunami10 commented Sep 18, 2018

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

@alexandcote

This comment has been minimized.

Copy link

@alexandcote alexandcote commented Sep 18, 2018

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

@PaddyLock

This comment has been minimized.

Copy link

@PaddyLock PaddyLock commented Sep 19, 2018

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

@ghost

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@VitaliiK91 VitaliiK91 commented Nov 9, 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.

@Winglonelion

This comment has been minimized.

Copy link

@Winglonelion Winglonelion commented Nov 9, 2018

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

@PaddyLock

This comment has been minimized.

Copy link

@PaddyLock PaddyLock commented Nov 11, 2018

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

@daibertdiego

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@daibertdiego daibertdiego commented Nov 15, 2018

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

This comment has been minimized.

Copy link

@mahesh-vidhate mahesh-vidhate commented Nov 29, 2018

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

This comment has been minimized.

Copy link

@helloitsm3 helloitsm3 commented Dec 2, 2018

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@RyuK-H 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

This comment has been minimized.

Copy link

@rollrodrig rollrodrig commented Dec 4, 2018

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

@shuangyu

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

@GuillaumeRZ

This comment has been minimized.

Copy link

@GuillaumeRZ GuillaumeRZ commented Jan 13, 2019

(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

@accept-li

This comment has been minimized.

Copy link

@accept-li accept-li commented Feb 26, 2019

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 👍

@wuxiii

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@sts-ryan-holton sts-ryan-holton commented May 13, 2019

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.

@amogh-jrules

This comment has been minimized.

Copy link

@amogh-jrules amogh-jrules 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

This comment has been minimized.

Copy link

@Biplovkumar Biplovkumar commented May 30, 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.

This is not the solution if i have oonly one https domain.

@hugosbg

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@Andersonfrfilho Andersonfrfilho commented Jul 14, 2019

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

This comment has been minimized.

Copy link

@Andersonfrfilho Andersonfrfilho commented Jul 15, 2019

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

This comment has been minimized.

Copy link

@fxbayuanggara fxbayuanggara commented Aug 23, 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'
}

OMG, you've saved my time bro!

@Rupeshiya

This comment has been minimized.

Copy link

@Rupeshiya Rupeshiya commented Aug 24, 2019

Nothing worked.
Is there any solution for this ?

@helloitsm3

This comment has been minimized.

Copy link

@helloitsm3 helloitsm3 commented Aug 24, 2019

What is the error?

@Rupeshiya

This comment has been minimized.

Copy link

@Rupeshiya Rupeshiya commented Aug 24, 2019

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

This comment has been minimized.

Copy link

@tayfunyasar tayfunyasar commented Sep 3, 2019

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

This comment has been minimized.

Copy link

@yasirlateef yasirlateef commented Sep 6, 2019

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

This comment has been minimized.

Copy link

@ivanguimam ivanguimam commented Nov 5, 2019

@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

This comment has been minimized.

Copy link
Collaborator

@yasuf yasuf commented Nov 5, 2019

is there anything to do on axios' end?

@helloitsm3

This comment has been minimized.

Copy link

@helloitsm3 helloitsm3 commented Nov 7, 2019

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

This comment has been minimized.

Copy link

@christian-hess-94 christian-hess-94 commented Dec 20, 2019

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

This comment has been minimized.

Copy link
Collaborator

@chinesedfan chinesedfan commented Dec 21, 2019

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

This comment has been minimized.

Copy link

@Olayinka-mumin Olayinka-mumin commented Jan 3, 2020

@ghost Super correct, 200% Right

@KBiswas98

This comment has been minimized.

Copy link

@KBiswas98 KBiswas98 commented Jan 31, 2020

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

http://192.168.43.49:3000/user/

@CLQueiroz

This comment has been minimized.

Copy link

@CLQueiroz CLQueiroz commented Mar 2, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
You can’t perform that action at this time.