Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Only Android] fetch Error : [Network request failed] #33217

Open
redvelvet-fan opened this issue Mar 3, 2022 · 42 comments
Open

[Only Android] fetch Error : [Network request failed] #33217

redvelvet-fan opened this issue Mar 3, 2022 · 42 comments
Labels
Needs: Triage 🔍 🌐Networking Related to a networking API. Platform: Android Android applications. Platform: iOS iOS applications.

Comments

@redvelvet-fan
Copy link

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(R) Core(TM) 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

@react-native-bot react-native-bot added Platform: Android Android applications. Platform: iOS iOS applications. 🌐Networking Related to a networking API. labels Mar 3, 2022
@redvelvet-fan redvelvet-fan changed the title fetch Error : [Network request failed] Only Android, iOS fine [Only Android] fetch Error : [Network request failed] Mar 3, 2022
@burakkaraceylan
Copy link

Have the same problem: [TypeError: Network request failed]

System:
OS: Windows 10 10.0.21996
CPU: (16) x64 AMD Ryzen 7 4800H with Radeon Graphics
Memory: 3.39 GB / 15.42 GB
Binaries:
Node: 17.0.1 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD
npm: 8.1.0 - C:\Program Files\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK: Not Found
Windows SDK: Not Found
IDEs:
Android Studio: Version 2021.1.0.0 AI-211.7628.21.2111.8139111
Visual Studio: Not Found
Languages:
Java: Not Found
npmPackages:
@react-native-community/cli: Not Found
react: 17.0.1 => 17.0.1
react-native: 0.64.3 => 0.64.3
react-native-windows: Not Found
npmGlobalPackages:
react-native: Not Found

@yteruel31
Copy link

Same problem :

System:
OS: Windows 10 10.0.19043
CPU: (12) x64 AMD Ryzen 5 2600 Six-Core Processor
Memory: 4.31 GB / 15.93 GB
Binaries:
Node: 14.18.2 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 7.24.2 -C:\Program Files\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK: Not Found
Windows SDK:
AllowDevelopmentWithoutDevLicense: Enabled
AllowAllTrustedApps: Enabled
Versions: 10.0.10240.0, 10.0.19041.0
IDEs:
Android Studio: Not Found
Visual Studio: 16.11.32002.261 (Visual Studio Community�2019)
Languages:
Java: javac 12 - C:\Program Files\Common Files\Oracle\Java\javapath\javac.EXE
npmPackages:
@react-native-community/cli: ^5.0.1 => 5.0.1
react: 17.0.2 => 17.0.2
react-native: 0.67.3 => 0.67.3
react-native-windows: Not Found
npmGlobalPackages:
react-native: Not Found

@burakkaraceylan
Copy link

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.

@Hashir524
Copy link

Any Update? Facing the Same Issue

@sergey-shablenko
Copy link

sergey-shablenko commented May 2, 2022

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

@geniuswe
Copy link

geniuswe commented May 31, 2022

Any Update? Facing the Same Issue

System:
OS: macOS 12.4
CPU: (8) x64 Intel(R) Core(TM) 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

@flyskywhy
Copy link
Contributor

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');
    }
  };

@arthurhts
Copy link

arthurhts commented Oct 26, 2022

I have the same problem here.
Problem occurs on old android, tested on android 6 and 7

Tested Versions

  • react-native: 0.70.2 and 0.70.4
  • axios: 0.21.4 - 0.27.2
  • targets sdk 31 and 33

@ugglr
Copy link

ugglr commented Nov 9, 2022

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.

@CraCrayon
Copy link

I have a similar problem, If you directly use the instance of new FormData() to assemble the Form Data parameter, you will be prompted [AxiosError: Network Error]

  • react 18.1.0
  • react native 0.70.2
  • axios 0.27.2
  • FLIPPER_VERSION 0.125

for example:

export function login(data) {
  const formData = new FormData()
  formData.append('username', data.username)
  formData.append('password', data.password)
  return axios.post('/api/user/login', formData)
}

It will prompt [AxiosError: Network Error]

But I used the following two methods to make the request successful:

    1. string
export function login(formData: LoginDataType) {
  const data = `username=${formData.username}&password=${formData.password}`
  return axios.post('/api/user/login', data)
}
    1. use 'qs'
import axios from 'axios'
import qs from 'qs'

export function login(formData: LoginDataType) {
  return axios.post('/api/user/login', qs.stringify(formData))
}

I don't know if the situation is the same as yours. I hope I can help you.

Sorry, my English is poor

@fwestling-lor
Copy link

Same as ugglr, it was working fine on RN 0.66.4 but upgrading to 0.70 caused it to stop working; same fetch request (uploading a file using FormData) works fine on iOS but throws a FETCH_ERROR on android; stringifying doesn't seem to help.

@DiogoMarques2003
Copy link

Any update ? i'm getting this error trying send a file in request

@fwestling-lor
Copy link

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

@DiogoMarques2003
Copy link

@fwestling-lor and if i send a pdf, is the same type ??

@DiogoMarques2003
Copy link

because this go block on backend, the backend system only accept pdf type

@DiogoMarques2003
Copy link

Ok this work for me thanks @fwestling-lor

@killuhwhale
Copy link

killuhwhale commented Feb 26, 2023

TL;DR
Do not add undefined for file information in form data.

This is strange. Over the last 2+ months, I was able to send a POST request w/ multipart/form-data where the images were undefined (when the user didn't add a file).

The request goes through and reaches the backend and my server responds to the request successfully.
However, the fetch reports the error [TypeError: Network request failed] and not the response from my server.

This became apparent on the frontend when my app didnt navigate back after the request was sent since an error was thrown.
What is strange is, I have haven't touched this bit of code in a while and all of a sudden it stopped behaving as expected and that's when I noticed the [TypeError: Network request failed] error.

Issue adding undefined values for file:

 data.append('main', {
      uri: mainFile.uri,
      name: mainFile.fileName,
      type: mainFile.type,
    });

// form data parts - data.getParts()
{"fieldName": "main", "headers": {"content-disposition": "form-data; name=\"main\""}, "name": undefined, "type": undefined, "uri": undefined}

@MythriKishan
Copy link

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.

@Liptor
Copy link

Liptor commented Jul 13, 2023

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

@DeveloperMCD
Copy link

I'm having the same issue today. It happens SOMETIMES. Other times, the image (FormData) posts and gets stored in the uploads folder (via a PHP script) just fine! Filesize doesn't seem to matter. Tried adding a 3 second delay. Did the "line 43 comment out" as well as ClearText in the Android.XML file. Pretty much tried EVERYTHING everyone has been suggesting. STILL having the problem.

@jr00n
Copy link

jr00n commented Aug 24, 2023

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

@krwadhwani
Copy link

After countless hours battling with the same issue, I figured out the problem. I was sending a dictionary as a value for one of the form keys. JSON.stringify the key worked. Also I had an audio file in the payload.

@snturk
Copy link

snturk commented Sep 29, 2023

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.

@GuillemGarciaDev
Copy link

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 🙏🏻

@DilipCoder
Copy link

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.

after adding the highlighted line in android/app/src/main/AndroidManifest.xml

Screenshot 2023-11-26 at 6 30 27 PM

then using serverbaseUrl(machine ipv4 address) as commented here.
working fine for me.

@dpietruc
Copy link

dpietruc commented Dec 1, 2023

@demon3z
Copy link

demon3z commented Dec 21, 2023

First of all, I solve by adding this in the upload request headers.

Connection: 'close',

I guess it happens with the HTTP connection.At the beginning, i use fetch ,but it throw Network request failed.And after i use rn-fetch-blob ,it throw unexpected end of stream.

@Ladvace
Copy link

Ladvace commented Jan 8, 2024

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

@kisaragi99
Copy link

@Liptor @DeveloperMCD
Hi guys, did you find a solution for this issue?

I do have same problem, it fails sometimes, like 1 fail for 3-4 success requests.
Tried to remove "Content-Type": 'multipart/form-data' and got constant errors with no success requests at all. (which is expectable).

@DiogoMarques2003
Copy link

@kisaragi99
Copy link

kisaragi99 commented Mar 4, 2024

Tried your approach (changed mime type to application/octet-stream)
Result is the same, fail, several successes and again fail.
Thanks.

Update.
Set up a mitmproxy to check requests and the problem vanished.
So, came to a conclusion that the problem was caused by some unknown to me network issues.

Probably the problem will not exist on a physical device.

@Gattanjo-Extrapreneur
Copy link

If the endpoint/url has underscores(_) in it you will get that error on Android.

@kisaragi99
Copy link

If the endpoint/url has underscores(_) in it you will get that error on Android.

Thank you, but my url does not have this symbol.

And the problem disappeared on production build.

Just don't have time to dig in this network issue, happy that it works.

@SaeedSoheili
Copy link

instead of :

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

use :

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

@ZLY201
Copy link

ZLY201 commented Mar 28, 2024

I have the same problem in production enviroment when I upload large file to backend large than 5M. But the nginx config accept files more than 10M+ and it's ok when send by browsers or postman.

It seems like some plugin in react-native reject the request when sending large files. I hope someone can tell me how to debug this.

RN Version 0.72.8.

@santirodriguezaffonso
Copy link

Using "image/jpeg" in type for Android as the comment above mentions solved the problem in my case. It wasn't required to change AndroidManifest.xml or ReactNativeFlipper.java.

So I ended up with an Asset like this:

formData.append(`assets_attribute`, {
   uri: image?.uri,
   type: Platform.select({ android: 'image/jpeg', default: image?.type || 'image' }),
   name: image?.fileName || imagesName(image?.uri),
}

I'm using RTK Query with headers: { 'Content-Type': 'multipart/form-data' }

"expo": "^49.0.0"
"react-native": "0.72.4"
"@reduxjs/toolkit": "^2.2.3"

@lemonadern
Copy link

lemonadern commented May 19, 2024

In my case, this code solved the problem.

// uri: string = body.imageUri;
const fd = new FormData();
fd.append('image', {
  uri,
  name: uri.split('/').pop(),
  type: 'image/jpeg',
} as any);

When specifying File or Blob objects as the second argument in the append method (as shown in MDN's FormData documentation), I encountered a Network request failed error.
However, it worked successfully when I specified an object in the mysterious format {uri: string, name: string, type: string}. Where can I find documentation for this interface?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs: Triage 🔍 🌐Networking Related to a networking API. Platform: Android Android applications. Platform: iOS iOS applications.
Projects
None yet
Development

No branches or pull requests