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

Network Error when send file with formData(axios or fetch) on Android. Works fine on IOS. #44657

Open
felipeavila-vp opened this issue May 23, 2024 · 11 comments
Labels
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. Needs: Triage 🔍 🌐Networking Related to a networking API. Platform: Android Android applications. Platform: iOS iOS applications.

Comments

@felipeavila-vp
Copy link

Description

When I try to send some post request sending a file with formData I receive a Network Error. Most of the time the request works fine, but sometimes I receive this error. The problem occurs when use Android, works fine with IOS.

Recently I updated my application to react-native 0.74.1(latest), before the version was 0.64.4. In older version all works fine.

Current versions:

  • React native: 0.74.1
  • Node: >= 18
  • React: 18.2.0
image

Steps to reproduce

Only try to submit some files using formData

React Native Version

0.74.1

Affected Platforms

Runtime - Android

Output of npx react-native info

System:
  OS: macOS 14.4
  CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
  Memory: 29.93 MB / 8.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 18.19.0
    path: /usr/local/bin/node
  Yarn:
    version: 1.22.22
    path: /usr/local/bin/yarn
  npm:
    version: 8.19.4
    path: /usr/local/bin/npm
  Watchman:
    version: 2024.05.06.00
    path: /usr/local/bin/watchman
Managers:
  CocoaPods:
    version: 1.15.2
    path: /usr/local/bin/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 23.4
      - iOS 17.4
      - macOS 14.4
      - tvOS 17.4
      - visionOS 1.1
      - watchOS 10.4
  Android SDK:
    API Levels:
      - "29"
      - "30"
      - "31"
      - "32"
      - "33"
      - "34"
    Build Tools:
      - 29.0.2
      - 30.0.2
      - 30.0.3
      - 31.0.0
      - 33.0.0
      - 33.0.1
      - 34.0.0
    System Images:
      - android-29 | Google APIs Intel x86 Atom
      - android-29 | Google Play Intel x86 Atom
      - android-30 | Intel x86_64 Atom
      - android-34 | Google APIs Intel x86_64 Atom
      - android-34 | Google Play Intel x86_64 Atom
      - android-VanillaIceCream | Google APIs Intel x86_64 Atom
    Android NDK: Not Found
IDEs:
  Android Studio: 2023.2 AI-232.10300.40.2321.11567975
  Xcode:
    version: 15.3/15E204a
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.10
    path: /usr/bin/javac
  Ruby:
    version: 2.6.10
    path: /usr/bin/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.74.1
    wanted: ^0.74.1
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: true
  newArchEnabled: false
iOS:
  hermesEnabled: true
  newArchEnabled: false

Stacktrace or Logs

No have logs to show

Reproducer

https://github.com

Screenshots and Videos

No response

@github-actions github-actions bot added Needs: Author Feedback Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. labels May 23, 2024
Copy link

⚠️ Missing Reproducible Example
ℹ️ We could not detect a reproducible example in your issue report. Please provide either:
  • If your bug is UI related: a Snack
  • If your bug is build/update related: use our Reproducer Template. A reproducer needs to be in a GitHub repository under your username.

@github-actions github-actions bot added Platform: Android Android applications. Platform: iOS iOS applications. 🌐Networking Related to a networking API. labels May 23, 2024
@H3tansh
Copy link

H3tansh commented May 31, 2024

This issue still in

const formData = new FormData()
formData.append('audio_file', {
name: fileName,
type: 'audio/mp3',
uri: filePath
})

    await fetch('http endpoint', {
        body: formData,
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
            Authorization:
                'Bearer token'
        }
    })
        .then(res => {
            console.log('test result ', res)
            console.log('test result status ', res.status)
        })
        .catch(e => {
            console.log('test e ', e)
        })

This returns network error

REACT-NATIVE-INFO output:-

System:
OS: macOS 14.2.1
CPU: (8) arm64 Apple M1
Memory: 599.88 MB / 16.00 GB
Shell:
version: "5.9"
path: /bin/zsh
Binaries:
Node:
version: 18.19.0
path: ~/.nvm/versions/node/v18.19.0/bin/node
Yarn:
version: 3.6.4
path: /opt/homebrew/bin/yarn
npm:
version: 10.2.3
path: ~/.nvm/versions/node/v18.19.0/bin/npm
Watchman:
version: 2024.04.15.00
path: /opt/homebrew/bin/watchman
Managers:
CocoaPods:
version: 1.15.2
path: /opt/homebrew/bin/pod
SDKs:
iOS SDK:
Platforms:
- DriverKit 23.0
- iOS 17.0
- macOS 14.0
- tvOS 17.0
- watchOS 10.0
Android SDK:
API Levels:
- "27"
- "28"
- "29"
- "30"
- "31"
- "32"
- "33"
- "34"
Build Tools:
- 27.0.3
- 28.0.3
- 29.0.2
- 29.0.3
- 30.0.2
- 30.0.3
- 31.0.0
- 32.0.0
- 32.1.0
- 33.0.0
- 33.0.0
- 33.0.1
- 34.0.0
System Images:
- android-32 | Google APIs ARM 64 v8a
- android-33 | Google APIs ARM 64 v8a
Android NDK: Not Found
IDEs:
Android Studio: 2023.1 AI-231.9392.1.2311.11330709
Xcode:
version: 15.0/15A240d
path: /usr/bin/xcodebuild
Languages:
Java:
version: 21.0.2
path: /usr/bin/javac
Ruby:
version: 2.6.10
path: /usr/bin/ruby
npmPackages:
"@react-native-community/cli": Not Found
react:
installed: 18.2.0
wanted: 18.2.0
react-native:
installed: 0.74.1
wanted: 0.74.1
react-native-macos: Not Found
npmGlobalPackages:
"react-native": Not Found
Android:
hermesEnabled: true
newArchEnabled: false
iOS:
hermesEnabled: true
newArchEnabled: false

@saadkhan2211
Copy link

Same issue here..

const fileExtension = coverImage.split(".").pop();

  // Create a new FormData instance
  const formData = new FormData();

  formData.append("image", {
    uri: coverImage,
    name: "image-" + new Date() + `.${fileExtension}`,
    type: `image/${fileExtension}`,
  } as any);

  // Append other form fields to FormData
  formData.append("food_name", data.food_name);
  formData.append("description", data.description);
  formData.append("price", String(data.price));
  formData.append("category", data.category);
  formData.append("addOn", JSON.stringify(data.addon));

  // Append sizes if applicable
  if (isSize && data.size.length > 0) {
    data.size.forEach((input, index) => {
      formData.append(`size[${index}]`, input.size);
      formData.append(`size_price[${index}]`, String(input.price));
    });
  }

  const response = await axios.post(
    `${app_url}/addMenuItem/${resId}`,
    formData,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );

When I console.log req.file and req.body,

undefined [Object: null prototype] {
food_name: '',
description: '',
price: 'null',
category: '',
addOn: '{"addon":"","price":0}'
}

Here I'm not sending any data in req.body only sending file to req.file which I get undefined..
This works fine with react native 0.73.x but not with 0.74.x

Copy link

github-actions bot commented Jul 1, 2024

This issue is waiting for author's feedback since 24 days. Please provide the requested feedback or this will be closed in 7 days.

@github-actions github-actions bot added the Stale There has been a lack of activity on this issue and it may be closed soon. label Jul 1, 2024
@felipeavila-vp
Copy link
Author

Same problem here yet

@github-actions github-actions bot added Needs: Attention Issues where the author has responded to feedback. and removed Needs: Author Feedback Stale There has been a lack of activity on this issue and it may be closed soon. labels Jul 5, 2024
@huzhanbo1996
Copy link
Contributor

@saadkhan2211 @felipeavila-vp @H3tansh Hi, could you provide Missing Reproducible Example as above, so I can help you solve this problem?

@H3tansh
Copy link

H3tansh commented Jul 12, 2024

@huzhanbo1996  below is my working code, It only works if I use deployed HTTPS API URL , but do not work if I use HTTP endpoint running on my localhost.

 const formData = new FormData()


    formData.append('file', {
        uri: path,
        name: fileName, // 'sound.mp3'
        type: fileType // 'audio/mp3'
    })

const response = await fetch(
    'https://dummy.url.com/api,
    {
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: `Bearer ${TOKEN}`
        },
        body: formData
    }
)

P.S:- Issue only persist in android.

here is the issue I've created
#44737

@raphpay
Copy link

raphpay commented Oct 24, 2024

Same here, but with windows.
It appears to be a problem only with multipart/form-data.
I got the same code running on all platforms, but windows is the only one causing trouble, and only with this method :

static async postFormData<T>(
    endpoint: string,
    data: any = {},
    token?: string,
  ): Promise<T> {
    try {
      const url = `${API_BASE_URL}/${endpoint}`;

      const headers: Record<string, string> = {
        'Content-Type': 'multipart/form-data',
      };

      // Include token in headers if provided
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch(url, {
        method: HttpMethod.POST,
        headers,
        body: data,
      });

      if (!response.ok) {
        let errorMessage = `HTTP error! Status: ${response.status}`;
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          const responseData = await response.json();
          if (responseData && responseData.reason) {
            errorMessage = responseData.reason;
          }
        }
        throw new Error(errorMessage);
      }

      return (await response.json()) as T;
    } catch (error) {
      throw error;
    }
  }

@saadkhan2211
Copy link

Hi Everyone, Mine got fixed after some troubleshooting...All I did was that I removed Content-Type part from headers and It worked

@jocoders
Copy link

jocoders commented Nov 5, 2024

I had the same problem after upgrade React Native to 0.72.17. And in my case renamed from Content-Type => content-Type fixed the error.

@sssajjad007
Copy link

same issue,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
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. 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

8 participants
@huzhanbo1996 @sssajjad007 @jocoders @raphpay @saadkhan2211 @felipeavila-vp @H3tansh and others