facebook / react-native

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

React Native 0.62.* [TypeError: Network request failed] on file upload #28551

Closed abumostafa closed 4 years ago

abumostafa commented 4 years ago

Please provide all the information requested. Issues that do not follow this format are likely to stall.

Description

After upgrading from 0.61.4 to 0.62.0 the app will not upload files anymore from Android (all other requests are working fine)

React Native version:

0.62.0

Steps To Reproduce

  1. Install a fresh ReactNative app via CLI
  2. Upload a file to the emulator
  3. Try to upload a file using fetch

import Picker from "react-native-image-picker"
import {request, PERMISSIONS, RESULTS} from 'react-native-permissions';

class App extends React.Component {

  async componentDidMount() {

    try {
      await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE)
      await Picker.launchImageLibrary({noData: true}, async (file) => {
        try {
           const body = new FormData()
           body.append("file", { type: file.type, size: file.fileSize, uri: `file://${file.path}`, name: file.fileName })
           const headers = { "content-type": "multipart/form-data", "accept": "application/json" }

          const req = await fetch("ANY_SERVER/upload/image", {
            method: "POST",
            headers,
            body
          })
          console.log(req.status)
        }  catch (e) {
          console.log(e)
        }
      })
    } catch (e) {
      console.log(e)
    }
  }

  render(){
    return <View/>
  }
}

Expected Results

The request should reach the server to upload the file

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

https://snack.expo.io/01W!bybf_ [Mon Apr 06 2020 21:29:18.704] LOG [TypeError: Network request failed]

carlezzo commented 4 years ago

Same problem here!

adityamohta commented 4 years ago

Same problem !! I am stuck on this issue from last 2 days! Searched almost everything..

HaidarZ commented 4 years ago

You need to add this uesCleartextTraffic="true" to the AndroidManifest.xml file found inside the dir android/app/src/main/AndroidManifest.xml

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

According to docs

When the attribute is set to "false", platform components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of confidentiality, authenticity, and protections against tampering; a network attacker can eavesdrop on transmitted data and also modify it without being detected.

adityamohta commented 4 years ago

You need to add this uesCleartextTraffic="true" to the AndroidManifest,xml file found inside the dir android/app/src/main

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

According to docs

When the attribute is set to "false", platform components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of confidentiality, authenticity, and protections against tampering; a network attacker can eavesdrop on transmitted data and also modify it without being detected.

I have tried it already. This is used when you are making request to a http server, but my server is running on https. It was running perfectly before upgrading to 0.62. Something is wrong.

adityamohta commented 4 years ago

All other requests are working perfectly. Only file uploads are not working anymore.

HaidarZ commented 4 years ago

All other requests are working perfectly. Only file uploads are not working anymore.

I faced too many issues when I tried upgrading to 0.62 even though I created a new app and moved my code into it. I rolled back to 0.61.5 till it gets stable :/

MateuszRostkowski commented 4 years ago

I am facing the same issue, for RN 0.62.0 and 0.62.1 throws this error: Network request filed. All requests work except for the image post

adityamohta commented 4 years ago

I moved back to 0.61.5 :( No other choice left for now. If anyone needs help in downgrading to 0.61.5, refer to react-native-upgrade-helper.

preko96 commented 4 years ago

Same happens here!

alfianwahid commented 4 years ago

I faced same issue, it happens in Android, but works well in IOS. I guess this issue about Flipper Network.

For while, I commented initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

in this file /android/app/src/main/java/com/{your_project}/MainApplication.java

trglairnarra commented 4 years ago

This issue occurs also on my end, and guess what it is only occurring in debug mode. Tried building in internalRelease and it works fine. I guess it is because of the auto/fast reload in debug mode which applies some flipper communication which seems to be related in this issue..

Another issue here is that there is no error in android logcat.. I've also spent some days researching how to fix this issue still no luck.

abumostafa commented 4 years ago

Whoever is still struggling with this issue. it's happening because of Flipper network plugin. I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

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

in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java

safaiyeh commented 4 years ago

Thanks for the issue @abumostafa. Does this occur in a fresh React Native template out of the box? If so this should be looked at otherwise feel free to close it.

github-actions[bot] commented 4 years ago
:warning: Missing Reproducible Example
:information_source: It looks like your issue is missing a reproducible example. Please provide a Snack or a repository that demonstrates the issue you are reporting in a minimal, complete, and reproducible manner.
github-actions[bot] commented 4 years ago
:warning: Using Old Version
:information_source: It looks like you are using an older version of React Native. Please upgrade to the latest version, and verify if the issue persists. If it does not, please let us know so we can close out this issue. This helps us ensure we are looking at issues that still exist in the current release.
alfianwahid commented 4 years ago

Thanks for the issue @abumostafa. Does this occur in a fresh React Native template out of the box? If so this should be looked at otherwise feel free to close it.

This still occurs in latest fresh React Native template 0.62.1

abumostafa commented 4 years ago

Thanks for the issue @abumostafa. Does this occur in a fresh React Native template out of the box? If so this should be looked at otherwise feel free to close it.

This still occurs in the latest fresh React Native template 0.62.1

@safaiyeh I can confirm. It's still happening in the latest fresh react native template 0.62.1

Daavidaviid commented 4 years ago

Whoever is still struggling with this issue. it's happening because of Flipper network plugin. I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

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

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Still happening in 0.62.2, and this fixes temporarily the issue on Android

Winplaybox commented 4 years ago

@abumostafa

Try this

try to implement "rn-fetch-blob"

import RNFetchBlob from "rn-fetch-blob";

RNFetchBlob.fetch('POST', <YOURURL>, {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',}, [
 { name: 'profileimage', filename: this.state.filePath.fileName, data: RNFetchBlob.wrap(this.state.filePath.uri) },
        { name: 'uid', data: uidy },
        { name: 'dob', data:this.state.fDOB},
        { name: 'phonenumber', data:this.state.pnumber},
        { name: 'address', data:this.state.address},
        { name: 'gender', data: this.state.isgender},
        { name: 'username', data: this.state.fulname}
        // custom content type
    ]).then((res) => {
        console.log(res)
        ResponseHelper.success('Updated');
        this.setState({isstarting:false})
    })
    .catch((err) => {
        this.setState({isstarting:false})
        ResponseHelper.success('Server issue please try again');
        console.log('err', error);
    })
Winplaybox commented 4 years ago

this will solve your issue

abumostafa commented 4 years ago

RNFetchBlob.wrap

Thanks. I have a question. Is this function RNFetchBlob.wrap converting the file to base64?

Julious1994 commented 4 years ago

Whoever is still struggling with this issue. it's happening because of Flipper network plugin. I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

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

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Thanks @abumostafa This workaround solution saved my lot of time. Already i spent lot of time on file upload error then i got your issue. By the way Did you know issue is fixed or not?

safaiyeh commented 4 years ago

I pinged the Flipper team, the work for this will be tracked here: https://github.com/facebook/flipper/issues/993

AugustoMarcelo commented 4 years ago

I tried the two solutions proposed by @abumostafa and @alfianwahid; I tried to downgrade to 0.61.5; I tried to implement with fetch (I'm using axios); none worked. I am using version 0.62.1

abumostafa commented 4 years ago

I tried the two solutions proposed by @abumostafa and @alfianwahid; I tried to downgrade to 0.61.5; I tried to implement with fetch (I'm using axios); none worked. I am using version 0.62.1

did you try to rebuild the app after the changes??

AugustoMarcelo commented 4 years ago

@abumostafa I don't know if I did it right. But I deleted the node_modules folder, yarn.lock, ran the commands ./gradlew clean and ./gradlew cleanBuildCache and ran npx react-native run-android again.

emad-ir commented 4 years ago

I am experiencing the same issue at the moment on RN 0.61.4 and axios 0.19.2. Also tried commenting initializeFlipper(this); cleanBuildCache and still getting Network Error.

brandtiwari007 commented 4 years ago

open the android folder and search for ReactNativeFlipper.java file and comment the line number 43 // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Anujmoglix commented 4 years ago

In my case, I don't have that file in my project

brandtiwari007 commented 4 years ago

In my case, I don't have that file in my project do you have android folder if you have search inside app folder

Winplaybox commented 4 years ago

RNFetchBlob.wrap

Thanks. I have a question. Is this function RNFetchBlob.wrap converting the file to base64?

https://github.com/joltup/rn-fetch-blob/wiki/Fetch-API#class-rnfetchblob

antoinerousseau commented 4 years ago

Same here, for example trying to fetch("https://www.mocky.io/v2/5185415ba171ea3a00704eed") raises a TypeError: Network request failed. It happens in Android only, both in debug and release, and both with remote debugging and without. Adding android:usesCleartextTraffic="true" didn't help (but it's for non-SSL requests anyway). Using RN 0.62.2.

Edit: fetching https://jsonplaceholder.typicode.com/todos/1 works! How can some sites work and others not?!

antoinerousseau commented 4 years ago

Update, after doing some tests, we came to the conclusion that it's due to failing SSL certificates. We don't know what's wrong with these, but the issue also happens in Postman with the "SSL certificate verification" option enabled. Could it be that the certificate authority is not in the phone's list?

marcodafonseca commented 4 years ago

Just spent the last day fighting with this issue. Prefixing my absolute path with "file://" so you end with three /'s sorted the issue out for me.

An example path:

file:///data/data/com.fake/cache/file-name.jpeg

Example of my code:

fetch(url, {
  method: "POST",
  body: {
    uri: 'file://' + file.absolutePath,
    type: file.type,
    name: file.name,
  },
  headers: headers,
  credentials: "include",
})

I am using react-native@^0.62.2

aprilmintacpineda commented 4 years ago

Has the fix been released? How do we update?

Hard-Haad commented 4 years ago

Still getting it in 0.62.2, are there any updates on this ?

Hard-Haad commented 4 years ago

Whoever is still struggling with this issue. it's happening because of Flipper network plugin. I disabled it and things work just fine. My workaround to make this work is commenting out line number 43

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

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Still happening in 0.62.2, and this fixes temporarily the issue on Android

This does fix it for now.

nabilalilipaly commented 4 years ago

Whoever is still struggling with this issue. it's happening because of Flipper network plugin. I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

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

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

this made my day! works fine with RN 0.62.0. thank you!

aprilmintacpineda commented 4 years ago

Flipper has published an update, please check out the latest comment https://github.com/facebook/flipper/issues/993#issuecomment-619823916 Will react-native publish an update to reflect this fix?

aprilmintacpineda commented 4 years ago

Still getting a Network request failed with that new Flipper 0.39.0 when trying to fetch("https://www.mocky.io/v2/5185415ba171ea3a00704eed"), even though it works in Chrome/Firefox/Safari.

@antoinerousseau You might want to say it there... I haven't tested it out.

antoinerousseau commented 4 years ago

@aprilmintacpineda I posted in https://github.com/facebook/react-native/issues/26939 instead, seems more related, and I'm not sure if it's Flipper related?

alfianwahid commented 4 years ago

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See : https://github.com/facebook/flipper/issues/993#issuecomment-619823916

shintabmt commented 4 years ago

i got the same issue with react 0.61.4

buddy1014 commented 4 years ago

Thanks @alfianwahid Solved my issue.

abumostafa commented 4 years ago

can we close this ticket?

durdevic commented 4 years ago

Helped me as well 💪

vendroid12 commented 4 years ago

@abumostafa , Thanks bro, that saved my 48 hours search

longebane commented 4 years ago

can we close this ticket?

I'm confused. Why are you wanting to close this issue if you only found a workaround and the issue was not fixed?

ivanalexo commented 4 years ago

Hi everybody, I also tried with axios and fetch but none of this worked, also I tried commenting the Flipper line and upgrading it but also it doesn't have effect. If you guys still having problems with this, better try to do your POST request with XMLHttpRequest it worked for me. Hope it helps.

khushal87 commented 4 years ago

This issue occurs also on my end, and guess what it is only occurring in debug mode. Tried building in internalRelease and it works fine. I guess it is because of the auto/fast reload in debug mode which applies some flipper communication which seems to be related in this issue..

Another issue here is that there is no error in android logcat.. I've also spent some days researching how to fix this issue still no luck.

How did you solve it ? @trglairnarra