facebook / react-native

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

TypeError: Network request failed On Android #25244

Closed keyz23 closed 5 years ago

keyz23 commented 5 years ago

Hi Everyone, I found this problem on my React-Native Android App. When I using a fetch to communicate with a working api, this type of error is returned to me.

TypeError: Network request failed

I Used the Chrome debbuger and I found this:

TypeError: Network request failed at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394) at XMLHttpRequest.js:507 at RCTDeviceEventEmitter.emit (EventEmitter.js:181) at MessageQueue.__callFunction (MessageQueue.js:366) at MessageQueue.js:106 at MessageQueue.__guard (MessageQueue.js:314) at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)

This is the code that I used:

`static creaUtente(identity, FirstName, LastName, FiscalCode , Email) { let formdata = new FormData(); formdata.append('Identity', identity); formdata.append('FirstName', FirstName); formdata.append('LastName', LastName); formdata.append('FiscalCode', FiscalCode); formdata.append('Email', Email);

    console.log(Configuration.base_url.rest + Configuration.apiRoutes.signUp)
    console.log(formdata)

    return new Promise((resolve, reject)=> {
        fetch('https://linktotheapi.com',{
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formdata
        })
        .then((response) => response.json())
        .then((responseData) => {
            if(responseData.Error){
                Alert.alert("Errore");
            }
            global.utente = responseData;
            resolve(responseData)
        })
        .catch((err) => {reject(err)})
    })
}`

I manually tried to use the API and it works. So the problem is fetch. I have seen and read that a lot have encountered this problem on android without a real solution.

The API link is a link type: https: //****.com (it is not a localhost). I tried to use the http version of the API but the error still appears.

Now, This is my package.json

dependencies": { "@react-native-community/async-storage": "^1.4.2", "buffer": "^5.2.1", "pouchdb-adapter-asyncstorage": "^6.4.1", "pouchdb-authentication": "^1.1.3", "pouchdb-find": "^7.0.0", "pouchdb-react-native": "^6.4.1", "react": "16.8.3", "react-native": "0.59.4", "react-native-ble-manager": "^6.6.2", "react-native-ble-plx": "^1.0.3", "react-native-json-tree": "^1.2.0", "react-native-keyboard-aware-scroll-view": "^0.8.0", "react-native-router-flux": "^4.0.6", "react-native-tab-navigator": "^0.3.4", "react-native-vector-icons": "^6.4.2" }, "devDependencies": { "@babel/core": "7.4.3", "@babel/runtime": "7.4.3", "babel-jest": "24.7.1", "jest": "24.7.1", "metro-react-native-babel-preset": "0.53.1", "react-test-renderer": "16.8.3" }, "jest": { "preset": "react-native" } }

I have read that this problem is on Android Device ( I obviously added internet permissions in the Manifest file ). Do you know nothing about this problem??

LegalPlatform commented 2 years ago

After Wasting one day finally I solve it !!

It was working on real host, but not on production environment, So, what I did I past ipconfig command in cmd in windows.

Then I got my ip address from IPv4 Address and past it in fetch variable instead of localhost.

tuoxiansp commented 2 years ago

For me, it was solved in a quite simple way:

headers: {
  // ...
}

->

headers: new Headers({
  // ...
})
sedhha commented 2 years ago

Well to summarize it all, this definitely is not a problem with React Native. I have tested it well with all the scenarios, here are the things you might consider when you get this error:

  1. Toggle between localhost and actual IP network (Very unlikely but worth a try, if you're requesting to global endpoint, then this step is not required.)
  2. Make sure you're connected to Internet (In case you're using emulator, try to open a browser or something)
  3. Make sure you're able to reach the endpoint with some other request client (Postman or any other HTTP client)

If you carefully examine above three, you would automatically find out what's missing, if you do the above in order, I am very sure you should be able to sort it out. Tested it with React 0.64.3

flyskywhy commented 2 years ago

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

vshy108 commented 2 years ago

For me, I appended file:// to android uri then the issue is solved while iOS does not need the append of file://

rychel commented 2 years ago

after this, if the problem persist don't forget disabled firewall

samad324 commented 1 year ago

I'm still getting this error even after adding android:usesCleartextTraffic="true" in AndroidManifest.xml file.

so i added my domain name in network_security_config.xml file.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <!-- deny cleartext traffic for React Native packager ips in release -->
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
        <domain includeSubdomains="true">10.0.3.2</domain>
        <domain includeSubdomains="true">domain.com</domain>
    </domain-config>
</network-security-config>

don't forget to add android:networkSecurityConfig="@xml/network_security_config" in your AndroidManifest.xml file.

 <application
     ...
      android:usesCleartextTraffic="true"
      android:networkSecurityConfig="@xml/network_security_config"
      ... >
vladimirevstratov commented 1 year ago

Solve HTTP and HTTPS Network request failed issue in react native fetch

https://infinitbility.com/network-request-failed-in-react-native-fetch

In my case it was an issue with expired TLS certificate of domain, found it by checking TLS status of domain.

SpaceSimon commented 1 year ago

I have a "Network request failed", only on Android and only with DELETE requests, both in development and production.

The deletion works fine but the request fails so I cannot update the UI.

I have this in my headers (among other things):

Accept: "application/json; version=13.0;"
Content-Type: "application/json"

RN version is 0.63.5

shahzaib803 commented 1 year ago

That solution worked for me .

I believe in my case it was failing when I only had the header for Content-Type: "multipart/form-data" as that was enough to make it work on iOS. But, on Android, I also had to specify that I wanted JSON back with the header Accept: "application/JSON". Simply specified both and 💥.

fvalles commented 1 year ago

To anyone still having this issue: I faced the same problem when trying to connect my react native app (android simulator & iOS physical device) to a local BFF.

The solution was not using the URL as http://localhost:PORT or http://127.0.01:PORT, but to use the real IPv4 IP address of my laptop which can be found on macOS navigating to: System settings -> Network -> WiFi (in my case) -> Details -> TCP/IP

GeorgeFlorian commented 12 months ago

This worked for me on EXPO SDK 49: I've installed expo-build-properties using npx expo install expo-build-properties and then added it as a plugin in app.json:

    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "usesCleartextTraffic": true
          }
        }
      ]
    ]
03balogun commented 9 months ago

Here's how I resolved this.

The server expects multipart/form-data for file uploads, but it seems that the request is being sent with application/x-www-form-urlencoded instead. This discrepancy causes the server to reject the request on Android, it works fine on iOS.

The native error looks like this

Failed to send url request: http://redacted-host-url.com/upload
java.lang.IllegalArgumentException: multipart != application/x-www-form-urlencoded
    at okhttp3.MultipartBody$Builder.setType(MultipartBody.kt:241)
    at com.facebook.react.modules.network.NetworkingModule.constructMultipartBody(NetworkingModule.java:688)
    at com.facebook.react.modules.network.NetworkingModule.sendRequestInternal(NetworkingModule.java:442)
    at com.facebook.react.modules.network.NetworkingModule.sendRequest(NetworkingModule.java:236)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
    at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:188)
    at com.facebook.jni.NativeRunnable.run(Native Method)
    at android.os.Handler.handleCallback(Handler.java:874)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
    at android.os.Looper.loop(Looper.java:198)
    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:228)
    at java.lang.Thread.run(Thread.java:764)

Explicitly setting the content type via the header fixed the issue.

Adding multipart/form-data to the request header fixed the issue for me.


headers: {
        'Content-Type': 'multipart/form-data'
      }
Buddhaa97 commented 9 months ago

@03balogun worked for me. Thanks