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

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

Closed
abumostafa opened this issue Apr 6, 2020 · 308 comments
Closed
Labels

Comments

@abumostafa
Copy link

abumostafa commented Apr 6, 2020

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
Copy link

carlezzo commented Apr 6, 2020

Same problem here!

@adityamohta
Copy link

adityamohta commented Apr 6, 2020

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

@HaidarZ
Copy link

HaidarZ commented Apr 6, 2020

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
Copy link

adityamohta commented Apr 6, 2020

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
Copy link

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

@HaidarZ
Copy link

HaidarZ commented Apr 6, 2020

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
Copy link

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
Copy link

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
Copy link

preko96 commented Apr 7, 2020

Same happens here!

@alfianwahid
Copy link

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
Copy link

trglairnarra commented Apr 8, 2020

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
Copy link
Author

abumostafa commented Apr 8, 2020

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
Copy link
Contributor

safaiyeh commented Apr 8, 2020

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.

@safaiyeh safaiyeh added Tool: Flipper Platform: Android Android applications. Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. Newer Patch Available and removed Tool: Flipper Platform: Android Android applications. labels Apr 8, 2020
@github-actions
Copy link

github-actions bot commented Apr 8, 2020

⚠️ Missing Reproducible Example
ℹ️ 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
Copy link

github-actions bot commented Apr 8, 2020

⚠️ Using Old Version
ℹ️ 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
Copy link

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
Copy link
Author

abumostafa commented Apr 8, 2020

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

@github-actions github-actions bot added Needs: Attention Issues where the author has responded to feedback. and removed Needs: Author Feedback labels Apr 8, 2020
@safaiyeh safaiyeh removed Needs: Attention Issues where the author has responded to feedback. Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. labels Apr 8, 2020
@ThangNguyen1998
Copy link

RN Version - 0.63.4
Flipper - 0.54.0.
I have facing same issue. I have changed Flipper version to 0.41.0. Now issue fixed. Thanks

not working in my case.

Hi , If you upload image set type : 'image/jpeg',

@vinod-bluebash
Copy link

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

Hey @abumostafa, What in the case of managed workflow like Expo where there is no access to native project files, what could be the possible solution in that case ?

@vinod-bluebash
Copy link

This solution worked for me:

https://forums.expo.io/t/network-request-failed-while-uploading-image-to-server/30737/5

I've got it please refer this resolution in case of Expo's managed workflow.

@AmirDiafi
Copy link

This issue solved in react-native 0.63.3+

@vinod-bluebash
Copy link

This issue solved in react-native 0.63.3+

Ok, So I feel the point is made clear that the issue is while trying to send invalid file validated attributes like invalid file uri, type or in case some missing required data attributes like name, while the issue being resolved.

@mirfanahmed
Copy link

Hello. I am facing a problem from past 2 days in android that whenever I try to hit an api through axios by simply sending a formdata I get a network error. I have updated to expo sdk 41 and react native version 0.63.3 but it still it gives me this error. I need urgent help.

@kylanhurt
Copy link

Still having same issues in RN 64.1

@itajenglish
Copy link

@mirfanahmed and @kylanhurt I fixed this issue by hard coding the file type extention. Take a look at the uriParts variable and fileType variable. Let me know if this works for you.

  const createFormData = (photo) => {
    const data = new FormData();
    const uriParts = photo.uri.split('.');
    const fileType = uriParts[uriParts.length - 1];

    data.append('image', {
      name: 'profilePic',
      type: `image/${fileType}`,
      uri: Platform.OS === 'ios' ? photo.uri.replace('file://', '') : photo.uri,
    });

    return data;
  };

@ruida-shen
Copy link

@mirfanahmed and @kylanhurt I fixed this issue by hard coding the file type extention. Take a look at the uriParts variable and fileType variable. Let me know if this works for you.

  const createFormData = (photo) => {
    const data = new FormData();
    const uriParts = photo.uri.split('.');
    const fileType = uriParts[uriParts.length - 1];

    data.append('image', {
      name: 'profilePic',
      type: `image/${fileType}`,
      uri: Platform.OS === 'ios' ? photo.uri.replace('file://', '') : photo.uri,
    });

    return data;
  };

This works for me

@quachdev
Copy link

quachdev commented Jun 10, 2021

I am getting this issue now on 0.64.2. Uninstalling Flipper is not working either. Anytime I make a network request (not just file upload) I get TypeError: Network request failed on Android.

iOS works fine.

Edit: Managed to isolate the issue to a dependency that we are using.

@itajenglish
Copy link

itajenglish commented Jun 10, 2021

@quachdev Try adb reverse tcp:8081 tcp:8081

@quachdev
Copy link

adb reverse tcp:8081 tcp:8081

Tried and no luck. Same result. Have tried to invalidate cache and restart as well on Android Studio.

@ak2403
Copy link

ak2403 commented Jun 20, 2021

Same issue exists. The API call is working in a real device, but not in the emulator.

Now, my concern is, Should I worry that it doesn't work on emulator? It will be good if someone can answer this question, so that I can work with the real device until this issue is sorted out.

@3KINGZ
Copy link

3KINGZ commented Jul 13, 2021

I'm facing this issue i've literally tried everything
"react-native": "0.64.1",

@tohshine
Copy link

tohshine commented Jul 16, 2021

same issue I have tried all the solutions but doesn't work
"react-native": "0.64.1",

while the file is part of the append throws a network error

` let body = new FormData()
body.append('location', 'GOOGLE_DRIVE')
body.append('docType', 'MEANS_OF_IDENTIFICATION')
body.append('file', { ...attachment.file })
const data = await axios.post('/file/api/v1/storage/folder/file', body, config, {
onUploadProgress: (progress) => {
const { loaded, total } = progress;
const percentagProgress = Math.floor((loaded / total) * 100);

                /* dispatching peercentage */
                dispatch(fileUploadProgress(attachment.id, percentagProgress));
            },
        });
        /* dispatch success upload */
        dispatch(successFileUpload(attachment.id));
        console.log('success data', data);`

@itajenglish
Copy link

Can you guys update your comments with the code you're trying to execute.

@thanhhai16
Copy link

Can you guys please help me, I'm struggling with this, I tried all the way, but my code still sends [object Object] to server?
This was worked well in past at 0.59 .
Please help me

@itajenglish
Copy link

itajenglish commented Jul 16, 2021

same issue I have tried all the solutions but doesn't work
"react-native": "0.64.1",

while the file is part of the append throws a network error

` let body = new FormData()
body.append('location', 'GOOGLE_DRIVE')
body.append('docType', 'MEANS_OF_IDENTIFICATION')
body.append('file', { ...attachment.file })
const data = await axios.post('/file/api/v1/storage/folder/file', body, config, {
onUploadProgress: (progress) => {
const { loaded, total } = progress;
const percentagProgress = Math.floor((loaded / total) * 100);

                /* dispatching peercentage */
                dispatch(fileUploadProgress(attachment.id, percentagProgress));
            },
        });
        /* dispatch success upload */
        dispatch(successFileUpload(attachment.id));
        console.log('success data', data);`

What file is this logic in? Is it in the file with the component that's selecting the image from the file system or a separate file? @tohshine

@itajenglish
Copy link

itajenglish commented Jul 16, 2021

Can you guys please help me, I'm struggling with this, I tried all the way, but my code still sends [object Object] to server?
This was worked well in past at 0.59 .
Please help me

Update the comment with your RN code @thanhhai16

@ionbaratol
Copy link

react native 0.64
✅ adding the content type in headers solved the issue for me.

fetch(urls[i], {
              method: 'put',
              headers: {'Content-Type': `${contentType}; charset=utf-8`},
              body: binaryFile,
            })

@FratilaRuxandra
Copy link

Check first if your upload works with very small files ( for example, instead of uploading a video, upload a gif ). In my case, any file over 1 MB would return "TypeError: Network request failed".

After many attemps, it turns out that the problem was caused by me using localtunnel, which limited my maximum file size.

@FoolCoder
Copy link

i getting this in RN 0.64 , while i individually upload image or video but when i upload with image and video text it works fine

@princefishthrower
Copy link

princefishthrower commented Sep 13, 2021

@abumostafa - legend.

Two weeks. Two weeks of scratching my head why file uploads were working absolutely fine in iOS, but wouldn't work in Android. Commenting a single line in a dev-only relevant file makes it work.

Incredible.

I love my life.

@skywalker2013
Copy link

skywalker2013 commented Sep 16, 2021

i face same issue in RN 0.65.1. why close the issue? have any solution?

@juggernauts
Copy link

@abumostafa - legend.

Two weeks. Two weeks of scratching my head why file uploads were working absolutely fine in Android, but wouldn't work in iOS. Commenting a single line in a dev-only relevant file makes it work.

Incredible.

I love my life.

@princefishthrower - @abumostafa solution works for Android, how did you manage to resolve it for iOS? We are also facing this issue in iOS

@princefishthrower
Copy link

princefishthrower commented Sep 30, 2021

@juggernauts In my case the file upload endpoint (sendbird chat profile upload if it helps) was working on iOS well before I did this "fix". To help further, I use the react-native-image-crop-picker with iOS and send the following fields in my 'file':

const result = await ImagePicker.openPicker(imagePickerOptions);
const file = {
          uri: result.path,
          type: result.mime,
          name: "anyStringHoweveryouWantToDefineTheFileName",
};

Also, I had a huge typo in my comment, this fixed file uploads for Android - iOS was working the whole time. Sorry for any confusion that may have caused! The good news is if you have Android working, iOS should be easier - at least that's how it was in my case.

@Commaando
Copy link

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.

Every Time.even in rn 0.65

@facebook facebook locked as resolved and limited conversation to collaborators Oct 1, 2021
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Oct 1, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.