React-native: React-Native fetch, Network request failed. On android

Created on 15 Oct 2016  路  80Comments  路  Source: facebook/react-native

Hello, everything working fine on IOS but it's faild on Android

fetch('http://somesite.com/app/connect', { ........

Thank you before hand

Locked

Most helpful comment

The thing is, that iOS is running in a simulator and Android is running in an emulator.
The localhost is pointing to the environment in which the code is running. The emulator emulates a real device while the simulator is only imitating the device.
Therefore the localhost on Android is pointing to the emulated Android device. And not to the machine on which your server is running.
The solution is to replace localhost with the IP address of your machine.

All 80 comments

@Clcll please show the options of your fetch

My requests using axios are also failing:

axios.get(`http://localhost:5000/posts`)
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

And I get the following exception on browser:

Error: Network Error
    at createError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:84821:11)
    at XMLHttpRequest.handleError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:84693:8)
    at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:15132:15)
    at XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:30776:6)
    at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:30622:6)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:30716:52
    at RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:14371:23)
    at MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:12115:34)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:11986:8
    at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:11926:1)

fetch API returns the same error:

Code:

export const fetchPosts = () => {  
  return (dispatch, getState) => {
    return fetch(`${API_URL}/posts/all`)
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson)
      })
      .catch((error) => {
        console.error(error);
      });
  }
}

Error:
screen shot 2016-10-15 at 11 10 20 pm

Packages:

  "dependencies": {
    "axios": "^0.15.0",
    "classnames": "^2.2.5",
    "react": "15.3.2",
    "react-native": "0.35.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "redux-thunk": "^2.1.0"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-jest": "16.0.0",
    "babel-preset-react-native": "1.9.0",
    "jest": "16.0.1",
    "jest-react-native": "16.0.0",
    "react-test-renderer": "15.3.2"
  }

EDIT:
Solution for me was instead of using localhost:port for the API address, actually using an IP address of the server.

@woniesong92 did you set Allow Arbitrary Loads = YES in info.plist?

@dunhuang info.plist is for iOS, how is that going to have any effect in Android? I am confused. @Clcll has mentioned that it works in iOS and it doesn't work in Android...

@sudhirvkumar I was thinking @woniesong92 's issue is running in IOS and now I think I might be wrong.
As for @Clcll I think some of his fetch option may not be supported in Android.

Running into the same issue with Android using axios & fetch.
I am resorting to using a Native Module for Android as a temporary solution.

Hey, I think we really don't have enough information here to debug this problem. Stack Overflow might be better for this, that way someone else can help edit the question. I'm going to close this issue, I'd try Stack Overflow if I were you.

Actually I fixed my problem, I just used the IP address Port of my server that host my API.
There is an issue with the security certificate of my server the android.

Guys, I encountered this issue as well. What I know so far is that Fetch API works on newer Android devices whose is Android 5 or above. The issue now seems happened on an older device including Android 4.1, 4.2 and 4.4 and issues seems happened on RN 0.30 and newer.

Hi guys,

I also get this issue randomly with the app installed on my iOS device.
I have allowed Arbitrary Loads in my info.plist file.

As this thread has been closed, is there a topic where we can find help ?

@rcabral90 Could you detail your solution a bit? I'm using IP Address and port for the server that hosts my API, but it gives me the Network Error about once in 5-7 requests

EDIT: I'm using http, not https

I had the same issue on iOS, it is okie for first 4-5 requests but the error occur then, please suggest !

The thing is, that iOS is running in a simulator and Android is running in an emulator.
The localhost is pointing to the environment in which the code is running. The emulator emulates a real device while the simulator is only imitating the device.
Therefore the localhost on Android is pointing to the emulated Android device. And not to the machine on which your server is running.
The solution is to replace localhost with the IP address of your machine.

Same problem with a public facing webhost. Network request failed. On Android btw.

Edit: It seems different times between server and host caused this.

Also running on this issue now with devices running on Android version 4.. using React Native version 0.40.0

I am facing same problem on react native android emulator. Is there a fix or solution. Please reply.

How to replace localhost with IP address of my machine.

I am also facing that

Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion
http://stackoverflow.com/questions/5528850/how-to-connect-localhost-in-android-emulator

+1 how can I fix it?
Even I changed axios.get('localhost:3000/hello') to axios.get('127.0.0.1:3000/hello'), the problem still left.

Edit

@rderwin way I fix it. Thanks

I replaced fetch('http://localhost:3000/api/meetups') with the IP adress of my computer and it worked

use your ip address in place of localhost,It should work

@achakra21 @montrealks still it not working

I was also facing the issue and i replaced the localhost with my ip address and it worked.

How to solve this error, This error occur when network connection is lost, screenshot_1499843569

@StephanPartzsch - You solved my problem. Thanks a lot.
For others - Please put the IP address of the target server into your request.
localhost is conflicting with localhost of android emulator.

All credit goes to StephanPartzsch. Respect for you.

Same problem with ngrok service. Anybody solve right way?

PD: I can't use IP address, I need a special host on the request.

I'm facing this problem in Android (iOS I solved it)

`
let url = "https://some.domain.com";
let body = null;

    let headers = {
      'Content-Type': 'application/json',
    };

    fetch(url, {
      method: "GET",
      headers: headers,
      body: null
    })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.log(error));

`

Package.json

{ "react": "16.0.0-alpha.12", "react-native": "0.47.1", }

Error:

TypeError: Network request failed

at XMLHttpRequest.xhr.onerror (fetch.js:441)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:546)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:381)
at XMLHttpRequest.js:485
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:266)
at MessageQueue.js:103
at MessageQueue.__guard (MessageQueue.js:231)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:102)

@vibhor-pandey I still get this error. Can u fixed?

@rcabral90 How do i know the ip address of my localhost after connected phone to my computer?

@Tom29 , If you're using Mac, then go to Network Preference > Advance Setting (you can find the IP).

In Windows run command "ipconfig", this will show you the IP

@melihberberolu Still I'm finding searching for the solution.

if(I_findSolution === true){
POST_SOLUTION();
}else if(YOU_findSolution === true){
POST_SOLUTION();
}

@vibhor-pandey I'm changed nginx config ssl_ecdh_curve secp384r1 to ssl_ecdh_curve prime256v1 and fixed

@melihberberolu How can I change this SSL?

I have solved the error like Network error by just putting my local address.
how to find local address ?

ipconfig
IPv4 will be your local address.
const API_URL ="http://192.168.xx.x:3001/getData";
fetch(${API_URL}, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
phone_no : phone
})
})

Running into the same issue. +

Per @rderwin's comment, here's how I'm setting things up so they work no matter the environment:

import {Platform} from 'react-native'

const SERVER_URL = __DEV__ ?
  Platform.select({
    ios: "http://localhost:3000",
    android: "http://10.0.2.2:3000"
  }) :
  "https://my-production-url.com"

The only way for us was to use the ip address instead of domain name.

The problem still persists past localhost as well. iOS seems be working fine for me, but Android is not. Running Android sdk 23 - Marshmallow locally, with a POST request to https://some-domain/auth.
When connecting to the remote JS debugging, the problem is solved. It seems like routing it through the browser makes the request work fine. But when remote JS debugging is turned off, I still continue to get Network Request Failed.

Running react-native: 0.45.1

This is a popular thread. Above answer with 60+ thumbs up did the trick!

Is there an alternative to fetch for react-native which works? We cannot "substitute the IP" for a real-world domain running on https, because its cert relies on the domain-name to match. How are people working-around this? Native-code specific to each device?

yeah it works like a charm!! thanks @StephanPartzsch , we have to change localhost instead your IP address for example 201.165.1.3:port

Just to cover all the angles but you get the same error if the request is a post and your targeting a get.

Im facing the issue (Network request failed) on android

I get the same error using axios or fetch

This is the fetch request

fetch('https://rallycoding.herokuapp.com/api/music_albums') .then(response => response.json()) .then(data => { this.setState({ title: 'Loaded!!!' }); }) .catch((error) => console.log(error));

I've been googling around for a couple hours and nothing I have found has helped.
"react-native": "0.51.0"
"react": "16.0.0"
OS: Ubuntu 16.04
Also tried on MacOS X High Sierra

You might want to try putting 'Cache-Control': 'no-cache' in headers. Fixed similar error for me.

How to fix this error can someone clearly suggest it please
I am hitting a url "http://xyz.com" not "http://localhost:xyz/"
I am getting the same Network Error

My issue was the emulator had a dns server error. I fixed this by appending -dns 8.8.8.8 when running the emulator command.

I am not getting dns server error, i am getting Network Error as specified in top of the post

can anybody help please..?

With the dns issue I was having, when making a request, I would get a Network Error as specified above. Make sure your emulator has access to the internet is all I'm saying. Open the browser on the emulator and try to navigate to a webpage. That was simply what was going on with me. Good day.

Thank You very much @NxSxD
That was the exact problem.
I was wondering is there any other way instead of starting it through command prompt

I ran into this issue as well. I can confirm that this is an issue with the emulator and not with react-native.

I think the problem is that, localhost refers to the machine which a particular program runs on, that means that localhost for the android is the emulator itself so localhost/api/blabla is actually making a request to the emulator itself. (Please @mention me for corrections.)

I fixed it by replacing http://localhost:9000 with http://10.0.2.2:9000 as described in https://developer.android.com/studio/run/emulator-networking.html. Basically it forwards (I'm not sure if that's the right word for this) the request to the machine where the emulator runs on. However, it only works with http and not with https, which in my case I was using https.

If you know how to set it up so that it can connect to https, please @mention me.

@aprilmintacpineda I had the same issue and got it to work.

You can make an https request on a local server that has an unsigned ssl certificate using react-native-fetch-blob instead of the default fetch method and set { trusty: true } as seen here.

To make it easy, I abstracted my api logic to an api.android.js and api.ios.js that dictates whether to use fetch or RNFetchBlob.

I have android version 3.0.1 and I am accessing a remote server using fetch function .I checked the internet connection on my simulator but still I'm getting the same error. Please suggest .

@sjsn nice! I got your idea, in my case I'm using axios. I'll look it up later. Thanks!

@StephanPartzsch I just replaced localhost with my ip address. It is working fine.
But the thing is, the ip address is changing in every restart or changing WiFi connection.

Nothing is working for me...

The same problem on Android with image
img-2018-01-31-00-10-18

@monolithed I think that error is telling you exactly what's wrong. You are giving an object as a child of an element, that's not going to work. People will be able to help you more if you show us the code that could be the most relevant and related to that error.

@aprilmintacpineda, nope.

let body = new FormData();

body.append('image', {
    uri: image,
    name: 'image',
    type: 'image/jpeg', // This is important for Android!!
});

await fetch(url, { body });

@monolithed Did you managed to solve it yet? where is that code located in the cycle of your software?

@aprilmintacpineda, the problem has already been solved. That exception has occurred due to I forgot to pass the type field (required on Android)

how woniesong92 says... Solution for me was instead of using localhost:port for the API address, actually using an IP address of the server.

@vibhor-pandey i had the same problem and i fixed it by chaning server ssl to a paid ssl ,
we were using lets encrypt on server and when i checked ssl on this website https://www.ssllabs.com/ssltest/analyze.html we got grade B for some security reasons!

by the way I changed ssl and now we have grade A+ and it fixed my problem;
hope this helps someone

@AmirTahani some updates (including SSL) solved my problem 馃槃

I dont know how far this approach is good, but for me if I go to
Tools -> AVD Manager -> Choose my device and wipe the data.

Then re-run the reac-native run-android, it seems to fetch the results perfectly without any network errors.
But it doesnt make sense why this approach works.

@monolithed tnx mate! You have saved my day!

in Android i have a problem same too.
please help i have deadline project in my office.

let url = "https://www.domain.com"; // real domain not localhost
let body = null;

let headers = {
  'Content-Type': 'application/json',
  'key':'xxxxxxxx',
};

fetch(url, {
  method: "GET",
  headers: headers,
  body: null
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));

`

Package.json

{ "react": "16.0.0", "react-native": "0.50.0", }

Error:

TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativenode_moduleswhatwg-fetchfetch.js:441)
at XMLHttpRequest.dispatchEvent (C:HDSAndroidreact nativereactNativemtnode_modulesevent-target-shimlibevent-target.js:172)
at XMLHttpRequest.setReadyState (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:554)
at XMLHttpRequest.__didCompleteResponse (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:387)
at C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesvendoremitterEventEmitter.js:181)
at MessageQueue.__callFunction (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:302)
at C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:116
at MessageQueue.__guard (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:265)
at MessageQueue.callFunctionReturnFlushedQueue (C:HDSAndroidreact nativereactNativemtnode_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:115)

@akiramouto there is no any exact statement about this error.

1) Uninstall the App(first clear all the Cached Data of the App from mobile)

2) If 1st Solution doesn't work out, then change the SSL

3) The last solution is to some package version conflicts

Please check if you can access google.com in the simulator.
If not, just remove the simulator and install again

Sounds like a problem with certificate. https://stackoverflow.com/questions/48198757/cant-fetch-api-resource

I tested some sites with this tool https://www.digicert.com/help/ And the websites that have the error: SSL Certificate is not trusted, are the ones that cause the error, TypeError: Network request failed

In my case I had to specify the dns-server when starting up, which allowed me internet access.

The following on Mac:

cd ~/Library/Android/sdk/tools
emulator -list-avds

Will give you a list of emulators, then you will need to start one up with the DNS specified, e.g.

emulator -avd Nexus_7_2012_API_27 -dns-server 10.1.1.1

Also, in my config I was referring to a hostname that was configured in my /etc/hosts which seems to work for iOS emulator, but I have to go with the ip address on the android one.

# this worked for me
i have https and http on my server
my IP and port constant is rejecting request for security reason
and i can't use constant IP in my URL react native because it change periodicly
i started with
https://185.85.*:8080/api .. > it closed by sysadmin
http://185.85.*/api .. > it closed by sysadmin
http://mysite.com/api .. http manual
https://mysite.com/api .. https manul
and so on ...
and i suddenly tested with
https://www.mysite.com/api .. and it worked 馃槀馃槀馃槀馃槀
dont forget to test with WWW

For iOS you'd still need to change it the actual local ip.

In development mode for iOS React Native gets started on the device with reloading working through the local ip, so the app already has it. Maybe we could get access to it somehow in JS so we can avoid having to do it manually.

I'm using iOS simulator from XCode, Android emulator from Android Studio.

on Android it's 10.0.0.2, so you can do: http(s)//10.0.0.2:9000/put/other/url/here.
on iOS it's localhost, so you can do http(s)//localhost:9000/put/other/url/here.

@Clcll
I found the reason for this error.
when i fetch "https://xxxxx",I get this error.But when i fetch "http://xxxx",this error gone.So I guess that by default android do not support HTTPS.
I hope someone could tell me how to fix it.

@Wowgreat there are multiple reasons as to why HTTPS would fail, it could be with certificates. I've tested Android and iOS on HTTPS and both worked well, in fact, iOS does not allow HTTP instead it will force you to use HTTPS.

@aprilmintacpineda
Thank you telling me those, I am new one in react-native.It is worth mentioning that few days ago I get the same error on iOS.Finally I fixed by read https://github.com/NativeScript/NativeScript/issues/1881 and summarize then write in here https://www.codemanclub.cn/index.php/article/getArticleById/100.
Hope those is useful for you.

I'm working with React native and Flask REST API, i had the same issue.
And i fixed it by adding:

host= '0.0.0.0'

Example:
if __name__ == '__main__':
    app.run(debug=True, host= '0.0.0.0')

Thanks to @jhadjar

Just replace the link's https with http

Was this page helpful?
0 / 5 - 0 ratings