facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
118.26k stars 24.22k 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??

safciplak commented 4 years ago

ccept: "application/json"

is it works?

akhan118 commented 4 years ago

android/gradle.properties

Add this

FLIPPER_VERSION=0.50.0

pedrogarciyalopez commented 4 years ago

android/gradle.properties

Add this

FLIPPER_VERSION=0.50.0

that's worked for me.

@akhan118 thanks a lot dude!

dotfelixb commented 4 years ago

same problem looks like no body is fixing this problem

This is not a react native specific issue, is more of Android 9.

lorenz068 commented 4 years ago

It happens to me on Android 8 and "react-native": "0.62.2", I send my position to the server with almost the same payload and sometimes it just failed randomly

Liqiankun commented 4 years ago

@devkrkanhaiya What are the debug folders?

safaiyeh commented 4 years ago

Hi all, we have a discussion here tracking this: https://github.com/facebook/react-native/issues/28551

There are a series of workarounds, mentioned in the thread. Check it out!

Liqiankun commented 4 years ago

29845 For me case.

ed-ssemakula commented 4 years ago

@alanhalpern06 All should be well with these changes

- data.append('dateBegin', dateBegin); + data.append('dateBegin', dateBegin.toISOString()); - data.append('dateEnd', dateEnd); + data.append('dateEnd', dateEnd.toISOString());

- 'Content-Type': 'application/json', + 'Content-Type': 'multipart/form-data',

jsdude0220 commented 4 years ago

Same issues in here. Fetch does not work well in Andorid. Sometimes it returns error that is Network request failed. It works well only IOS. Is there any solutions to solve this?

Liqiankun commented 4 years ago

@Cocktails0921 #29845

jamesjara commented 4 years ago

Based on this code https://github.com/facebook/react-native/blob/476a336e3613f90b76e3a91d5bffaa098bf4e6ff/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java#L383 any request without headers content-type and payload body as string will start failing into "Network request failed." this is because the high-level wrappers are handing the Request Error call as "Network request failed." but is not even reaching the internet.

1.

    try {
      sendRequestInternal(
          method,
          url,
          requestId,
          headers,
          data,
          responseType,
          useIncrementalUpdates,
          timeout,
          withCredentials);
    } catch (Throwable th) {
      FLog.e(TAG, "Failed to send url request: " + url, th);
      ResponseUtil.onRequestError(getEventEmitter(), requestId, th.getMessage(), th);
    }
  }
  1. sendRequestInternal
    else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
      if (contentType == null) {
        ResponseUtil.onRequestError(
            eventEmitter, requestId, "Payload is set but no content-type header specified", null);
        return;
      }
lunoob 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)); } });

good ! this worked for me too. rn version: 0.63.1

pke commented 3 years ago

Is this something new that appeared in a patch release? Because when I started my RN project the same code I have now could connect to the https Server I'm using.

RahulDutta007 commented 3 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..

Thank you, it works. You're a God

SUMITIOS commented 3 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)

The same problem and solution in my case , XMLHttpRequests are working but fetch not. I am not using expo, RN version 0.62.2.

obendevski commented 3 years ago

Hey guys, I had the same problem. I was trying to upload audio .aac file via formData. For me, i had to prepend the uri part of the formData with file://.

Hope it helps someone.

the-smart-home-maker commented 3 years ago

Based on this code

https://github.com/facebook/react-native/blob/476a336e3613f90b76e3a91d5bffaa098bf4e6ff/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java#L383

any request without headers content-type and payload body as string will start failing into "Network request failed." this is because the high-level wrappers are handing the Request Error call as "Network request failed." but is not even reaching the internet.

    try {
      sendRequestInternal(
          method,
          url,
          requestId,
          headers,
          data,
          responseType,
          useIncrementalUpdates,
          timeout,
          withCredentials);
    } catch (Throwable th) {
      FLog.e(TAG, "Failed to send url request: " + url, th);
      ResponseUtil.onRequestError(getEventEmitter(), requestId, th.getMessage(), th);
    }
  }
  1. sendRequestInternal
else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
      if (contentType == null) {
        ResponseUtil.onRequestError(
            eventEmitter, requestId, "Payload is set but no content-type header specified", null);
        return;
      }

@jamesjara: Awesome! I just hat to add the "Content-Type" as "multipart/form-data" and "Accept" as "application/json".--> now it works fine

laurent22 commented 3 years ago

If that can help anyone, React Native 0.62+ seems to require a "Content-Type" header for certain fetch calls or else you get "Network request failed". More info in this issue: https://github.com/facebook/react-native/issues/30176

ecklf commented 3 years ago

android:usesCleartextTraffic="true"

Please avoid doing this.

You are most likely running into this issue because you are trying to develop locally with an emulator and don't have the correct URL (10.0.2.2 is the default for AVD).

import { Platform } from "react-native";
export const API_URL =
  Platform.OS === "ios" ? "http://localhost:4000" : "http://10.0.2.2:4000";

If you need a public URL use https://ngrok.com/ or set up a small VPS with https://certbot.eff.org/

Powersanth commented 3 years ago

its working for me url should be 10.0.2.2:3000/singup localhost will not work if you are sending from real android device use your pc ip address

bitfabrikken commented 3 years ago

For anyone searching and landing here, I got this error if I feed an array as a value to the FormData object used in the fetch request body. E.g., pseudocode, how to provoke the "TypeError: Network request failed" error on Android:

var formData = new FormData();
formData.append("test", [10,20,30]);

var res = await fetch("https://google.com",{
    method: "POST",
    headers: {  
        'Accept':       'application/json',
        'Content-Type': 'multipart/form-data',
    },
    body: formData
}).catch((err) => {  
    console.log("caught err",err);
});

Headers do not matter, just that it's a POST request.

youssef212 commented 3 years ago

what I found is when giving an empty form-data to fetch it fails as well with network request failed

LightSmileMu commented 3 years ago

"http://ip:port" format may be useful for android device.

Asimurrehman commented 3 years ago

I am also using "react-native": "0.63.2" my error Gone i did like this :

1)Added a comment // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); file path: android/app/src/debug/java/com/{your_project}/ReactNativeFlipper.java then Rebuild my App using 'yarn run android ' then every thing will successfully worked

my code πŸ‘

let body = new FormData();
body.append('submit', 'ok');
body.append('file', {
  uri: res.uri,
  name: res.fileName,
  type: res.type,
});
frankjosephbarbato commented 3 years ago

I had this issue and learned that with fetch you cannot use localhost. You must use the IP address of your computer on the network.

danieltaoxu commented 3 years ago

I had this issue and learned that with fetch you cannot use localhost. You must use the IP address of your computer on the network.

Oh my god, you saved me, it's that problem, do you know how to avoid use the IP address? it's so annoying .....

frankjosephbarbato commented 3 years ago

Not sure, I wonder if using the HTTP module has different behavior?

danieltaoxu commented 3 years ago

Not sure, I wonder if using the HTTP module has different behavior?

I'll try it. Thanks.

huynguyen0304 commented 3 years ago

Hope this issue will reopen.

Asimurrehman commented 3 years ago

my issue was solved

On Thu, Jan 21, 2021 at 12:33 PM huynguyen0304 notifications@github.com wrote:

Hope this issue will reopen.

β€” You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/facebook/react-native/issues/25244#issuecomment-764443020, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJ37VO2XTALRGE6X7NS5Y73S27KEPANCNFSM4HXTRC3Q .

johmedina commented 3 years ago

It's still not solved with me. I tried using my machine's IP address instead of localhost but that didn't work for me. Anyone else facing the same problem?

djuwon commented 3 years ago

Also having the same issue ^^^. I changed the localhost to computer ip as well. I'm debugging on a physical device. When I send a fetch request, the application crashes with no errors thrown.

johmedina commented 3 years ago

My issue was solved and the problem rooted from using react native and asp.net core. Basically, I needed to change the code from my .net API. In launchsettings.js , change "applicationUrl": "https://localhost:5001;http://localhost:5000" to "applicationUrl": "http://localhost:5000" and then react native can fetch from localhost using the IP address without any issues.

j-perl commented 3 years ago

I can't thank you enough @akhan118

android/gradle.properties

Add this

FLIPPER_VERSION=0.50.0

ZeeshanZafar557 commented 3 years ago

remove from-data solved in my case

var myHeaders = new Headers(); myHeaders.append("auth-token", ids.token); var formdata = new FormData(); var requestOptions = { method: 'PUT', headers: myHeaders, // body: formdata, redirect: 'follow' };

return fetch(baseUrl+"api/v1/trip/"+ids.uId+'/'+ids.tripId+'/views', requestOptions) .then(response => {

if(response.status==200)
{
  return response.json()
}
else {  
  return response.text()
}

}) .then(result => { return result }) .catch(error => console.log('error', error));

nilmeme commented 3 years ago

I changed api url 'localhost' to real host, it works!!! And 127.0.0.1 dons't work also

danieltaoxu commented 3 years ago

I changed api url 'localhost' to real host, it works!!! And 127.0.0.1 dons't work also

10.0.2.2 works for me , it can avoid to change every time restart the machine

Rolando-Barbella commented 3 years ago

My problem was I did not have internet connection on the emulator, pretty silly, hope it can help someone

petrosmm commented 3 years ago

Based on this code

https://github.com/facebook/react-native/blob/476a336e3613f90b76e3a91d5bffaa098bf4e6ff/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java#L383

any request without headers content-type and payload body as string will start failing into "Network request failed." this is because the high-level wrappers are handing the Request Error call as "Network request failed." but is not even reaching the internet.

    try {
      sendRequestInternal(
          method,
          url,
          requestId,
          headers,
          data,
          responseType,
          useIncrementalUpdates,
          timeout,
          withCredentials);
    } catch (Throwable th) {
      FLog.e(TAG, "Failed to send url request: " + url, th);
      ResponseUtil.onRequestError(getEventEmitter(), requestId, th.getMessage(), th);
    }
  }
  1. sendRequestInternal
else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
      if (contentType == null) {
        ResponseUtil.onRequestError(
            eventEmitter, requestId, "Payload is set but no content-type header specified", null);
        return;
      }

For posterity, I got it to work on the following: I am certain the above was important, if not, absolutely correct. In my case it did not affect the outcome. My scenario was the following: fresh RN TS project 0.62.2, Android 4.4, Https (secure) request, and Emulator mode (debug). I kept seeing "Network request field". I was able to get this to work on Genymotion emulator for 4.4 with Google Playstore (NEEDED -- from opengapps.org) and this piece of code. Here is my sample code:

function getTestRequest() {
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  headers.append('Accept', 'application/json');

  const configInit: RequestInit = {
    method: 'GET',
    // headers: headers
  };

  const url = 'https://www.csattv.org/menu.json'
    ?? 'https://jsonplaceholder.typicode.com/todos/1';

  fetch(url)
    .then(res => {
      console.log('\r\n res', res, '\r\n');
      return res.json();
    }).then(data => {
      console.log(data);
      return data;
    }).catch(p => {
      console.warn(p);
      return;
    });
}
infinitbility commented 3 years ago

Solve HTTP and HTTPS Network request failed issue in react native fetch

https://infinitbility.com/network-request-failed-in-react-native-fetch

Hel5ing commented 3 years ago

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

hey man,you are awesome!!

joe105598055 commented 3 years ago

If you are developing on mac and using wifi. Must remember add DNS (e.g. 8.8.8.8). It works for me.

ζˆͺεœ– 2021-06-17 上午9 20 49
alekseiaksenov commented 3 years ago

It's July-2021, and the problem has never been solved?

laurent22 commented 3 years ago

I think the core issue is the terrible error message. I mean it's a simply an HTTP request, it's plain text, so surely it's possible to get a proper error message from the underlying lib? eg "Missing header", "Invalid content type", etc.

When a user of my app sees a "Network request failed" I can only tell them there's pretty much no way to know what the error is. They have to randomly try every config variations on their server until it works. That's not how it should be in 2021 - HTTP requests are well understood, and it should be possible to surface a proper error message when something happens.

lorecast commented 3 years ago

Solve HTTP and HTTPS Network request failed issue in react native fetch

https://infinitbility.com/network-request-failed-in-react-native-fetch

Thanks, it's work for me

coldshine commented 3 years ago

I had the similar issue. I was setting incorrect type in FormData object: it was image instead of image/jpeg or image/png or image/whatever. My code was:

const formData = new FormData();
formData.append('image', {
  uri: imageUri,
  name: 'someName',
  type: 'image'
});

And the working one:

const uriParts = imageUri.split('.');
const fileType = uriParts[uriParts.length - 1];

const formData = new FormData();
formData.append('image', {
  uri: imageUri,
  name: 'someName',
  type: `image/${fileType}`
});
SANDEEP1938 commented 3 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 .

but this thing is not working for me

hieuplasma commented 3 years ago

I had fixid this problem in ubuntu and android real device. Folow these steps:

  1. In terminal, press "ifconfig" and copy ipadress of device, in my case is usb0
  2. Shake your device to open menu dev, choose "Dev settings" or "Settings"
  3. Choose Debug server host & port fort device, press ip:8081, in my case is 192.168..:8081
  4. Open terminal again, and press adb reverse tcp:3000 tcp:3000
  5. Now, you can request api with url http://localhost:3000/{params}
nilsond commented 2 years ago

I solved the problem with this video: https://www.youtube.com/watch?v=TNIz3P2r4rU

NOTE: This is for those who are using MAC