facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
118.18k stars 24.21k forks source link

TypeError: Network request failed On Android #25244

Closed keyz23 closed 5 years ago

keyz23 commented 5 years ago

Hi Everyone, I found this problem on my React-Native Android App. When I using a fetch to communicate with a working api, this type of error is returned to me.

TypeError: Network request failed

I Used the Chrome debbuger and I found this:

TypeError: Network request failed at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394) at XMLHttpRequest.js:507 at RCTDeviceEventEmitter.emit (EventEmitter.js:181) at MessageQueue.__callFunction (MessageQueue.js:366) at MessageQueue.js:106 at MessageQueue.__guard (MessageQueue.js:314) at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)

This is the code that I used:

`static creaUtente(identity, FirstName, LastName, FiscalCode , Email) { let formdata = new FormData(); formdata.append('Identity', identity); formdata.append('FirstName', FirstName); formdata.append('LastName', LastName); formdata.append('FiscalCode', FiscalCode); formdata.append('Email', Email);

    console.log(Configuration.base_url.rest + Configuration.apiRoutes.signUp)
    console.log(formdata)

    return new Promise((resolve, reject)=> {
        fetch('https://linktotheapi.com',{
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formdata
        })
        .then((response) => response.json())
        .then((responseData) => {
            if(responseData.Error){
                Alert.alert("Errore");
            }
            global.utente = responseData;
            resolve(responseData)
        })
        .catch((err) => {reject(err)})
    })
}`

I manually tried to use the API and it works. So the problem is fetch. I have seen and read that a lot have encountered this problem on android without a real solution.

The API link is a link type: https: //****.com (it is not a localhost). I tried to use the http version of the API but the error still appears.

Now, This is my package.json

dependencies": { "@react-native-community/async-storage": "^1.4.2", "buffer": "^5.2.1", "pouchdb-adapter-asyncstorage": "^6.4.1", "pouchdb-authentication": "^1.1.3", "pouchdb-find": "^7.0.0", "pouchdb-react-native": "^6.4.1", "react": "16.8.3", "react-native": "0.59.4", "react-native-ble-manager": "^6.6.2", "react-native-ble-plx": "^1.0.3", "react-native-json-tree": "^1.2.0", "react-native-keyboard-aware-scroll-view": "^0.8.0", "react-native-router-flux": "^4.0.6", "react-native-tab-navigator": "^0.3.4", "react-native-vector-icons": "^6.4.2" }, "devDependencies": { "@babel/core": "7.4.3", "@babel/runtime": "7.4.3", "babel-jest": "24.7.1", "jest": "24.7.1", "metro-react-native-babel-preset": "0.53.1", "react-test-renderer": "16.8.3" }, "jest": { "preset": "react-native" } }

I have read that this problem is on Android Device ( I obviously added internet permissions in the Manifest file ). Do you know nothing about this problem??

react-native-bot commented 5 years ago

Thanks for submitting your issue. Can you take another look at your description and make sure the issue template has been filled in its entirety?

👉 Click here if you want to take another look at the Bug Report issue template.

lucky-newbie commented 5 years ago

did you solve it? i met too...

keyz23 commented 5 years ago

No I haven't solve it...

keyz23 commented 5 years ago

Nobody?

Valiums commented 5 years ago

hey @keyz23 @823844596, I recently encountered something similar using fetch and formDatas (only on Android though). The workaround that worked for me was to use XMLHttpRequest instead of fetch. Hopefully this will help you too!

I don't know if you are using expo but for me this problem started when I updated my expo SDK from 31 to 33 (so RN 0.57.1 to 0.59.8)

amohit1315 commented 5 years ago

Was anyone able to solve it?? I am facing similar issue with fetch. I have to use common code for android and iOS. fetch works great in iOS but in android throws error.

Trying to fetch data from remote server via api. Using fetch(https:url:port) to fetch the data. But every time android emulator as well as physical device gives network request failed. While I can access same url within browser of emulator.

I have already went through various links, and many people have posted same problem but none of them had ample solution that works. While some people were not able to access localhost via api-call but it was resolved using IP address of system. But in my scenario I am trying to access remote host. Also domain name cannot be used in my scenario, so need a solution using (ip) in fetch method=get.

testlogin = https://10.209.7.115:8080/api/v1/ Basicauth = 'Basic cm9vdDpyb290'

fetch(testingLogin, { method: "GET", cache: "no-cache", mode: "cors", withCredentials: true, credentials: "include", headers: { 'Authorization':Basicauth, Accept: "application/json", "Content-Type": "application/json" } }).then(response => { if(response.status === 200) { this.props.navigation.navigate('Home'); } else { alert("Authorization failed"); } }) .catch(error => { alert("Request Failed :Check the ip address Entered:Problem with server "); throw(error);

   })

Error:

TypeError: Network request failed onerror@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:24051:31 dispatchEvent@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:28695:31 setReadyState@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:28448:33 didCompleteResponse@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:28275:29 emit@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:3280:42 callFunction@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2577:49 http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2334:31 __guard@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2531:15 callFunctionReturnFlushedQueue@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:2333:21

garrinmf commented 5 years ago

@keyz23 you closed the ticket, but did you find a fix for it?

IcebergRage commented 5 years ago

@keyz23 @garrinmf do you find a solution ?

garrinmf commented 5 years ago

@IcebergRage, I got past this, forgot I'd commented anywhere though and it's a bit fuzzy now.

I believe in my case it was failing when I only had the header for Content-Type: "multipart/form-data" as that was enough to make it work on iOS. But, on Android, I also had to specify that I wanted JSON back with the header Accept: "application/json". Simply specified both and đź’Ą.

ailton-moreira commented 5 years ago

I have the same issue. Did any one was able to solve it?

CYBERNEURONES commented 5 years ago

Why this issue is not fix ?

Dantalion commented 5 years ago

Same issue. Still no fix?

daybreaker commented 5 years ago

We're having the same issue here but on iOS. Using rn 0.53. It was working fine a while ago.

The weird thing is if I have RN Debugger open, our code works. But with remote debugging turned off, everything with fetch returns a Network Request Failed error.

I know that when RN Debugger is open, RN uses V8 to run the code, and when remote debugging is off, it uses the device/simulator's native JavaScriptCore... I wonder if the most recent version of iOS has an updated version of JavaScriptCore that implements fetch differently from V8?

I'm not educated enough in the internals of javascript engines to get much further than this, though.

Any help would be appreciated.

DodoTheDeveloper commented 4 years ago

Dear fellow developers, please check out my comment on the similar issue #24394 . I hope it will help some of you.

Lpaydat commented 4 years ago

I solved it but I'm not sure is it the same issue with you guys.

In my case, I used expo (in an android device) together with relay-modern and this error occurs when I try to fetch data from my server (localhost).

After spending an hour to find the solution with no results I just find out the source of my error. It is the fetch url (I used localhost and it works in the browser so I just forgot about it). When I change the url to the correct ip address, this issue have gone.

I hope this helps and sorry for my bad English.

EzeRangel commented 4 years ago

This is a problem with the cert. Your server should use intermediate certificates so Android should not reject the requests.

Papyrus0120 commented 4 years ago

issue is not fixed then y its closed

alanhalpern06 commented 4 years ago

I have the same problem here, the most curious thing is that this error just happen when it's a POST request, on my GET requests it's is working well. Somebody have any ideia?

On postMan my request Workswell too!

My code:

NetInfo.fetch().then(isConnected => {
            if(isConnected) {
                var url = "http://vvendas.com/api/home";
                var data = new FormData();                    
                data.append('dateBegin', dateBegin);
                data.append('dateEnd', dateEnd);
                data.append('format', 'json');
                fetch(url, {
                    method:'POST',
                    headers:{
                        'Accept': 'application/json', 
                        'Content-Type': 'application/json',
                        'Authorization': "Bearer "+ userToken
                      },
                    mode:"cors",
                    body: data,
                    redirect: 'follow'
                }).then(response => response.json())
                .then(resJSON => {

                    console.log('It WORKS',resJSON)
                }).catch(err => {
                     console.log(err)                  
                })
            }else{
                console.log('not Connected')
            }
        })

The terminal result : LOG [TypeError: Network request failed]

The Chrome Debbug (ctrol+m -> Debug) : TypeError: Network request failed at XMLHttpRequest.xhr.onerror (index.bundle?platfor…&minify=false:26748) at XMLHttpRequest.dispatchEvent (index.bundle?platfor…&minify=false:32302) at XMLHttpRequest.setReadyState (index.bundle?platfor…&minify=false:31386) at XMLHttpRequest.__didCompleteResponse (index.bundle?platfor…&minify=false:31213) at index.bundle?platfor…&minify=false:31323 at RCTDeviceEventEmitter.emit (index.bundle?platfor…e&minify=false:3316) at MessageQueue.__callFunction (index.bundle?platfor…e&minify=false:2648) at index.bundle?platfor…e&minify=false:2361 at MessageQueue.__guard (index.bundle?platfor…e&minify=false:2602) at MessageQueue.callFunctionReturnFlushedQueue (index.bundle?platfor…e&minify=false:2360)

ThalesCrisostomo commented 4 years ago

Anything about that?

alessiocancian commented 4 years ago

Had a similar problem after upgrading react native, the only way I was able to solve it is using RNFetchBlob, as shown here: https://stackoverflow.com/a/50061209/5724186

Baterka commented 4 years ago

I have same problem on RN 0.62 :( Working fine in release but in debug very annoying!

dotfelixb commented 4 years ago

Add this to your manifest

<application
    ...
    android:usesCleartextTraffic="true"
    ...>
    ...
</application>
devkrkanhaiya commented 4 years ago

step1> add android:usesCleartextTraffic="true" line in AndroidManifest.xml like:

<application ... android:usesCleartextTraffic="true"> // add this line ...

step2> Delete all debug folder from your android folder..

akhan118 commented 4 years ago

@dotfelixb @devkrkanhaiya work on RN .62 👆💕

Temirtator commented 4 years ago

@dotfelixb @devkrkanhaiya work on RN .62 👆💕

This solution doesnt solve my problem

dotfelixb commented 4 years ago

@Temirtator This is not a react native issue, is from Android so look into this, hope it helps

<application android:networkSecurityConfig="@xml/network_security_config"
                    ... >
        ...
    </application>

then create a file in your as res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.com</domain>
        <trust-anchors>
            <certificates src="@raw/my_ca"/>
        </trust-anchors>
    </domain-config>
</network-security-config>

you can read more at Network security configuration

Temirtator commented 4 years ago

@dotfelixb thanks for your answer. I found out, problem was with fetch request, so, to solve this problem, Im using RNFetchBlob(https://github.com/joltup/rn-fetch-blob) library, for sending files to server. But lately i'll check your solution.

amit-tanwar commented 4 years ago

step1> add android:usesCleartextTraffic="true" line in AndroidManifest.xml like:

<application ... android:usesCleartextTraffic="true"> // add this line ...

step2> Delete all debug folder from your android folder..

It worked for me "react-native": "0.62.2"

apostolou commented 4 years ago

@amit-tanwar, @devkrkanhaiya , @dotfelixb , I've tried to insert the line you mention (add android:usesCleartextTraffic="true" ) in the AndroidManifest.xml file but didn't manage to make this work because I don't find the path of the debug folder to delete. Could you please explicitely give the path ? thanks a lot!

dotfelixb commented 4 years ago

@apostolou the debug folder is at "project_name//android/app/src/debug", not there's also an AndroidManifest.xml file that needs android:usesCleartextTraffic="true" too.

apostolou commented 4 years ago

@dotfelixb thanks for your feedback. Deleting the folder didn't fix the issue đź‘Ž unfortunately. I switched to rn-fetch-blob to make my upload work.

amit-tanwar commented 4 years ago

@amit-tanwar, @devkrkanhaiya , @dotfelixb , I've tried to insert the line you mention (add android:usesCleartextTraffic="true" ) in the AndroidManifest.xml file but didn't manage to make this work because I don't find the path of the debug folder to delete. Could you please explicitely give the path ? thanks a lot!

Path is shared by @apostolou and hope you rebuild the app after following the steps. Usually (For me atleast) best approach is to close the metro server and restart with the command "react-native start --reset-cache" and rebuild the app.

cultofdev commented 4 years ago

same here, I can't get this to work with just a simple get request from a secured api, here is the snippet:

fetch('https://domainofapi/api/emp/position/all', { method: 'GET', cache: 'no-cache', mode: 'cors', headers: { 'Accept': 'application/json', }, }) .then(response => response.json()) .then(json => setPositions(json));

tried almost every solution I can find, usesCleartextTraffic, network security config, etc.

Brianop commented 4 years ago

@cultofdev Did you find a fix for this ?

cultofdev commented 4 years ago

@cultofdev Did you find a fix for this ?

No, after 3 days I just trashed the project and switched to flutter, and besides most of the suggested fixes that I found on the net is just a workaround and not even working..

dotfelixb commented 4 years ago

@cultofdev this is not a react-native bug, it's just the version of Android react-native is using

NSR88 commented 4 years ago

Add this to your manifest

<application
    ...
    android:usesCleartextTraffic="true"
    ...>
    ...
</application>

I already have this, but still not working :(

NSR88 commented 4 years ago

hey @keyz23 @823844596, I recently encountered something similar using fetch and formDatas (only on Android though). The workaround that worked for me was to use XMLHttpRequest instead of fetch. Hopefully this will help you too!

I don't know if you are using expo but for me this problem started when I updated my expo SDK from 31 to 33 (so RN 0.57.1 to 0.59.8)

I also tried using XMLHttpRequest, but its returning me error 406

export async function uploadXHR(url, data) {
  var formData = new FormData();
  for (let key in data) {
    formData.append(key, data[key]);

  }
  formData.append('jsonKey', {CompanyCode:"Demo3"});

  var xhr = new XMLHttpRequest();

  return new Promise(
    function (resolve, reject) {

      xhr.open("POST", url);

      xhr.onload = function () {
        if (this.status >= 200 && this.status < 300) {
          resolve(xhr.response);
        } else {
          // console.log('StatusText: '+xhr.statusText);
          reject({
            status: this.status,
            statusText: xhr.statusText
          });
        }
      };
      xhr.onerror = function () {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      };
      xhr.send();

    }
  );

}
Slals commented 4 years ago

Project on RN v0.63.0-rc.1

I'm also getting Network request failed without any other infos.

I tried :

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">mydomain.com</domain>
    </domain-config>
</network-security-config>

None worked, tried on a working URL, simple GET method. fetch is failing somewhere but I have no idea where it comes from. Anyone know how we can track this issue?

nkpatnis commented 4 years ago

Was facing same issue for RN 0.62.2 and was able to fix it by updating this https://github.com/jhen0409/react-native-debugger/releases to v0.11.3

cleartextTrafficPermitted="true" this should not be used in production until you know what you are doing.

josmithua commented 4 years ago

In my case it was only not working for localhost URLs. I changed localhost in the URL to my local IP and it worked. (RN 0.62.2)

f4z3k4s commented 4 years ago

As it seems nobody has been as careless as I were when running into this, but I'll give my two cents, hopefully it will help somebody save some time:

If above boxes are checked meaning that your requests work perfectly from a browser, you could try debugging the issue further. 🤗

PS: I've just tested it on a 5ish-year-old Lenovo device with Android 5.1 and it works, also my Pixel 2 emulator with API 29.

zcmgyu commented 4 years ago

Just not work on Android. android:usesCleartextTraffic="true" also does not thing

devkrkanhaiya commented 4 years ago

Just not work on Android. android:usesCleartextTraffic="true" also does not thing

Delete all debug folder from your android folder..

akmallmr commented 4 years ago

Not work on me..

yashwantt commented 4 years ago

step1> add android:usesCleartextTraffic="true" line in AndroidManifest.xml like:

<application ... android:usesCleartextTraffic="true"> // add this line ... step2> Delete all debug folder from your android folder..

Awesome this worked for me

asim47 commented 4 years ago

I fixed it by commenting a line in the /android/app/src/debug/java/com/{your-app-name}/ReactNativeFlipper.java file. this is only fix that worked for me!

new NetworkingModule.CustomClientBuilder() { @override public void apply(OkHttpClient.Builder builder) { // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } });

Kipsanga-Gregory commented 4 years ago

I fixed it by commenting a line in the /android/app/src/debug/java/com/{your-app-name}/ReactNativeFlipper.java file. this is only fix that worked for me!

new NetworkingModule.CustomClientBuilder() { @override public void apply(OkHttpClient.Builder builder) { // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } });

Thanks Buddy, this one worked for me too. However, is it cool to just have that function return nothing now that we commented out its return value? please someone let me know about this

Baterka commented 4 years ago

...However, is it cool to just have that function return nothing now that we commented out its return value?

Its void method :) it is not returning anything even when not commented ;)

tseringn commented 4 years ago

same problem looks like no body is fixing this problem