react-native: [Only Android] fetch Error : [Network request failed]

Description

—My Code—

const reverseGeocoding = async (location: Location) => {
    const params = new URLSearchParams({
        "orders": `admcode`,
        "output": "json",
        "coords": `${location.longitude},${location.latitude}`
    }).toString()
        const resultBare = await fetch(`${Config.REVERSE_GEOCODING_URL}?${params}`, {
            method: "GET",
            headers: {
                "X-NCP-APIGW-API-KEY-ID": `${Config.NCP_AI_CLIENT_ID}`,
                "X-NCP-APIGW-API-KEY": `${Config.NCP_AI_CLIENT_SECRET}`,
            }
        })
        const jsonResult = await resultBare.json()
        console.log(JSON.stringify(jsonResult))
        return jsonResult;
}

—Not working solution—

  1. android:usesCleartextTraffic=“true”
  2. commenting out line number 43 in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java
38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);
  1. Change FLIPPER_VERSION
27  # Version of flipper SDK to use with React Native
28  FLIPPER_VERSION=0.39.0  // edit this manually

its too old solution my code already 0.99.0

—Error—

Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:25357:33
http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:29572:26
_callTimer@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:29492:17
callTimers@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:29693:19
__callFunction@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:3056:36
http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:2780:31
__guard@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:3007:15
callFunctionReturnFlushedQueue@http://192.168.1.13:8081/index.bundle?platform=android&dev=true&minify=false&app={package.my.project}&modulesOnly=false&runModule=true:2779:21
callFunctionReturnFlushedQueue@[native code]

fetch not working only android emulators , physical device too

Version

0.66.4

Output of npx react-native info

System: OS: macOS 11.1 CPU: (16) x64 Intel® Core™ i9-9880H CPU @ 2.30GHz Memory: 3.60 GB / 32.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 17.3.1 - /usr/local/bin/node Yarn: Not Found npm: 8.3.1 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.2 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4 Android SDK: Not Found IDEs: Android Studio: 4.2 AI-202.7660.26.42.7351085 Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild Languages: Java: 11.0.9.1 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.66.4 => 0.66.4 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found

Steps to reproduce

just using fetch, axios etc… any networking tools

Snack, code example, screenshot, or link to a repository

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 9
  • Comments: 41 (1 by maintainers)

Most upvoted comments

For me, I was able to fix this by adding a mime-type of the file to the upload (wasn’t required previously or on iOS):

const chunk = {
   uri: `file://${file.path}`,
   type: "application/octet-stream", // I wasn't including this;  works if I use the proper type (e.g. image/jpeg) as well
   name: file.name,
   size: file.size
}
const formData = new FormData();
formData.append("Chunk", chunk);
formData.append("OtherData", data);

await axios.post("upload", formData, {
   headers: {
      "Content-Type": `multipart/form-data`, 
   },
});

Hope that helps someone

Any update? Same issue on any request. Neither adb -s <device> reverse tcp:8080 tcp:8080 nor network_security_config.xml nor usesCleartextTraffic helped

react-native: 0.68.1

Same issue

Any Update? Facing the Same Issue

Spent few hours and research a bit. There’s a problem on android with request url.

Condition 1: Not Working on Android

API: RTK Query Server base url: http://localhost:8080

Works well on iOS but not works on Android

Condition 1: Works in both platforms

API: RTK Query Server base url: http://192.168.1.1:8080 (ipv4)

Works well on both platforms.

I have the same issue, started happening after upgrading from RN 0.66.4 to 0.70.5

  • react-native: 0.70.5
  • react: 18.1.0
  • flipper: 0.125.0

I have also tried all the proposed solutions above without any success.

fixed TypeError: Network request failed when upload file to http not https with Android debug builds

In react-native 0.63.2 (I’m testing) or some higher version, if just use fetch to upload file to a http (not https) server, will meet TypeError: Network request failed.

Here I use axios@0.27.2 as client running on an Android phone successfully upload a file to react-native-file-server as server running on another Android phone.

client need edit JAVA and JS code, server no need edit JAVA code.

With debug builds, must commenting out line number 43 in this file android/app/src/debug/java/com/YOUR_PACKAGE_NAME/ReactNativeFlipper.java

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

Maybe also need add android:usesCleartextTraffic="true" under <application of android/app/src/main/AndroidManifest.xml , on my test, it’s not necessary on both debug and release builds.

  onFileSelected = async (file) => {
    // API ref to the server side BE code `addWebServerFilter("/api/uploadtodir", new WebServerFilter()`
    // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L356
    // could not be 'localhost' but IP address
    const serverUploadApi = 'http://192.168.1.123:8080/api/uploadtodir';

    // the folder on server where file will be uploaded to, could be e.g. '/storage/emulated/0/Download'
    const serverFolder = '/storage/emulated/0/FileServerUpload';

    const fileToUpload = {
      // if want to upload and rename, it can be `name: 'foo.bar'`, but can not be 'foo'
      // only if your server upload code support file name without type, on our server
      // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L372
      // will cause java.lang.StringIndexOutOfBoundsException in substring()
      name: file.name,

      // type is necessary in Android, it can be 'image/jpeg' or 'foo/bar', but can not be
      // 'foo', 'foo/', '/foo' or undefined, otherwise will cause `[AxiosError: Network Error]`
      type: 'a/b',

      uri: Platform.OS === 'android' ? file.uri : file.uri.replace('file://', ''),
    };

    const form = new FormData();
    form.append('path', serverFolder);
    form.append('uploadfile', fileToUpload);

    // ref to the server side FE code `this.axios.post("/api/uploadtodir", parms, config)`
    // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/fileserverwebdoc/src/views/Manage.vue#L411
    let res = await axios.post(serverUploadApi, form, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: function (progressEvent) {
        console.warn(progressEvent);
      },
    });

    // ref to the server side BE code `return newFixedLengthResponse("Suss");`
    // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L380
    if (res.data === 'Suss') {
      console.warn('Upload Successful');
    } else if (res.data === 'fail') {
      console.warn('Upload Failed');
    }
  };

I have same issue. It works on iOS, but not on Android. By the way, sending first picture in post request fails, but second is ok, third in not etc. Nothing suggested in the sources helps

For me, I was able to fix this by adding a mime-type of the file to the upload (wasn’t required previously or on iOS):

const chunk = {
   uri: `file://${file.path}`,
   type: "application/octet-stream", // I wasn't including this;  works if I use the proper type (e.g. image/jpeg) as well
   name: file.name,
   size: file.size
}
const formData = new FormData();
formData.append("Chunk", chunk);
formData.append("OtherData", data);

await axios.post("upload", formData, {
   headers: {
      "Content-Type": `multipart/form-data`, 
   },
});

Hope that helps someone Thank You. This Solved the Issue.

In my case, I was trying to upload a file with multipart/form-data but apparently fetch can’t handle blob files. It works fine if I don’t append the file but fails with an uninformative error if I do. I now use rn-fetch-blob which can handle uploading binary data.

For me, I was able to fix this by adding a mime-type of the file to the upload (wasn’t required previously or on iOS):

const chunk = {
   uri: `file://${file.path}`,
   type: "application/octet-stream", // I wasn't including this;  works if I use the proper type (e.g. image/jpeg) as well
   name: file.name,
   size: file.size
}
const formData = new FormData();
formData.append("Chunk", chunk);
formData.append("OtherData", data);

await axios.post("upload", formData, {
   headers: {
      "Content-Type": `multipart/form-data`, 
   },
});

Hope that helps someone

Awesome!! You saved my day!! I work with RTK Query and only had to change the type in the FormData files chunk. Indeed only on Android…on iOS is was fine before and stil is with type: “application/octet-stream”

I had this problem with Expo 49 and RN 0.7.2.4

instead of :

       headers: {
          "Content-Type": "application/json",
        },

use :

        headers: {
          "Content-Type": "multipart/form-data",
        },

I was using EXPO_PUBLIC_API_URL="http://localhost:3000" for my local API requests, replacing localhost with my IP seems working

POSIBLE SOLUTION

I faced the same problem (iOS working & Android failure) and in the end it turned out to be a problem because the domain to which the request was made contained an underscore (_) character. Removing the underscore by a dash solved the problem.

Previos domain https://my_domain.com

Working domain https://my-domain.com

If you are using a domain other than localhost and use special characters it is possible that it may fail because of this. I will update my comment if I find any additional information.

I hope it helps 🙏🏻

any update on this?

Any Update? Facing the Same Issue

System: OS: macOS 12.4 CPU: (8) x64 Intel® Core™ i7-4870HQ CPU @ 2.50GHz Memory: 509.63 MB / 16.00 GB Shell: 5.8.1 - /bin/zsh Binaries: Node: 16.14.2 - ~/.nvm/versions/node/v16.14.2/bin/node Yarn: 1.22.15 - ~/.nvm/versions/node/v16.14.2/bin/yarn npm: 8.5.0 - ~/.nvm/versions/node/v16.14.2/bin/npm Watchman: 2022.03.21.00 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.3 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5 Android SDK: API Levels: 30, 31, 32 Build Tools: 30.0.2, 30.0.3, 31.0.0, 32.0.0, 32.1.0 System Images: android-30 | Google APIs Intel x86 Atom Android NDK: Not Found IDEs: Android Studio: 2021.1 AI-211.7628.21.2111.8193401 Xcode: 13.4/13F17a - /usr/bin/xcodebuild Languages: Java: 11.0.11 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: 0.68.1 => 0.68.1 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found