36

I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
    at XMLHttpRequest.js:493
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:353)
    at MessageQueue.js:118
    at MessageQueue.__guardSafe (MessageQueue.js:316)

This is my axios call in my react native component:

    componentDidMount() {
        axios.get('mydomain.com/get/').then(response => {  // localhost:8000/get works
            this.setState({foo:response.data});
        }).catch(error => {
            console.log(error);
        });
    }
smilebomb
  • 5,123
  • 8
  • 49
  • 81
  • You probably want to have some sort of logger to see the request and response to make sure what the actual network error is – Sean Wang Mar 19 '18 at 20:10
  • Is this happening on iOS, Android, or both? – ajthyng Mar 19 '18 at 21:34
  • @SeanWang Is there something you were thinking of? I'm not sure what you mean. – smilebomb Mar 20 '18 at 01:06
  • @ajthyng iOS, haven't tried android. – smilebomb Mar 20 '18 at 01:06
  • 1
    Possible duplicate of [Axios (in React-native) not calling server in localhost](https://stackoverflow.com/questions/42189301/axios-in-react-native-not-calling-server-in-localhost) – Rex Low Mar 20 '18 at 01:28
  • Possible duplicate of [React Native fetch() Network Request Failed](https://stackoverflow.com/questions/38418998/react-native-fetch-network-request-failed) – Michael Cheng Mar 20 '18 at 01:35
  • The solution to these error can vary and the error message is not very helpful. For those that might still run into the same problem, if you want to get helpful error messages that will help you debug, use `console.log(error.response)`. I spent a whole day before I saw this in [axios documentation](https://axios-http.com/docs/handling_errors) – SirG Mar 15 '22 at 22:18

14 Answers14

64

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.

Esteban Vega
  • 741
  • 6
  • 4
40

It seems that unencrypted network requests are blocked by default in iOS, i.e. https will work, http will not.

From the docs:

By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception.

smilebomb
  • 5,123
  • 8
  • 49
  • 81
  • Also, if you're connecting to a remote host, make sure that your SSL intermediate certificates are correctly established. Use https://www.digicert.com/help/ to check them. – Mostafa Farzán Nov 21 '20 at 22:34
  • I have https but it's doesn't work yet do you know another way for this ? – MEAbid Jun 08 '21 at 12:39
  • @smilebomb please check this https://stackoverflow.com/questions/75180455/how-to-soul-payment-gateway-using-stripe-error-in-react-native –  Jan 23 '23 at 04:25
  • please check this https://github.com/axios/axios/issues/5366 – Cinorid May 20 '23 at 06:08
26

If you do not find your answer in other posts

In my case, I use Rails for the backend and I tried to make requests to http://localhost:3000 using Axios but every time I got Network Error as a response. Then I found out that I need to make a request to http://10.0.2.2:3000 in the case of the android simulator. For the iOS simulator, it works fine with http://localhost:3000.

Conclusion

use

http://10.0.2.2:3000

instead of

http://localhost:3000

update

might worth trying

adb reverse tcp:3000 tcp:3000
Shiva
  • 11,485
  • 2
  • 67
  • 84
  • 1
    http://localhost:3000 it's doesn't work for IOS and then I changed the http to https it's still doesn't work – MEAbid Jun 08 '21 at 12:41
  • @MEAbid make sure ip and port is correct. Also, check firewall settings. – Shiva Jun 09 '21 at 01:31
22
  1. change from localhost to your ip(192.168.43.49)
  2. add http://

    http://192.168.43.49:3000/user/

kamalesh biswas
  • 883
  • 8
  • 9
4

Try "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json"

bhaRATh
  • 716
  • 4
  • 23
3

For me, the issue was because my Remote URL was incorrect. If you have the URL is a .env file, please crosscheck the naming and also ensure that it's prefixed with REACT_APP_ as react might not be able to find it if named otherwise.

In the .env file Something like REACT_APP_BACKEND_API_URL=https://appurl/api can be accessed as const { REACT_APP_BACKEND_API_URL } = process.env;

Cryce Truly
  • 139
  • 1
  • 5
3

If you are using android then open your command prompt and type ipconfig. Then get your ip address and replce it with localhost.

In my case, first I used http://localhost:8080/api/admin/1. Then I changed it to http://192.168.1.10:8080/api/admin/1. It worked for me.

0

I was facing the same issue.

i looked deeper and my

endpoint url was not correct.

By giving axios right exact url, my api worked like charm.

Hope it may help anyone

Muhammad Ashfaq
  • 2,359
  • 5
  • 20
  • 46
0

Make sure to change localhost to your_ip_address which you can find by typing ipconfig in Command Prompt

Trying adding to your AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

enestatli
  • 535
  • 1
  • 9
  • 19
0

Above mentioned answers only works if you are using localhost but if your code is hosted on a server and Axios throwing Network Error then you can solve this by adding one line.

const config = {
  method: 'post',
  url: `${BASE_URL}/login`,
  headers: { 
    'Content-Type': 'multipart/form-data'.  <----- Add this line in your axios header
  },
  data : formData
};


  axios(config).then((res)=> console.log(res))
Muhammad Haidar
  • 1,541
  • 16
  • 17
0

I'm using apisauce dependancy & Adding header work for me with React Native Android.

Attach header with request like below:

import { create } from 'apisauce';

    const api = create({
    baseURL: {baseUrl},
    headers: {
                Accept: 'application/json',
               'Content-Type': 'application/json'
             }
    });

export async function empLogin(data) {
   try {
         const response = api.post('Login', data);
         return await response;
   } catch (error) {
         console.log(error);
         return [];
   }
}
ShraOne Devade
  • 199
  • 1
  • 5
0

before: axios.get("http://localhost:3456/apt") .then( response => { alert(JSON.stringify(response)); .... } ) .catch(function(error) { alert(error.message); console.warn(error.response._response);

});

I get Error "Network error" Failed to connect to the localhost after that, I make some steps to resolved the error.

Network Error related to axios resloved by the disabling the system firewall and access from the system IP Address like

axios.get("http://192.168.12.10:3456/apt") .then( response => { alert(JSON.stringify(response)); .... } ) .catch(function(error) { alert(error.message); console.warn(error.response._response);

});
Mohsin
  • 7
  • 3
0

For me adding "Accept" in headers resolved the problem:

Accept: 'application/json'
Hamza Khursheed
  • 2,399
  • 2
  • 15
  • 17
0

If you are having issues while connecting to localhost from react-native app. you can do following steps

1- goto cmd type ipconfig. 2- replace localhost with your ip version 4 3- try again.. it will succeed.

it works for me.

Waheed Khan
  • 104
  • 2
  • 10