React native android network error

Hello, everything working fine on IOS but it's faild on Android fetch('http://somesite.com/app/connect', { ........ Thank you before hand

My requests using axios are also failing:


axios.get(`http://localhost:5000/posts`)
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

And I get the following exception on browser:

Error: Network Error
    at createError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:84821:11)
    at XMLHttpRequest.handleError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:84693:8)
    at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:15132:15)
    at XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:30776:6)
    at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:30622:6)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:30716:52
    at RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:14371:23)
    at MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:12115:34)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:11986:8
    at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false:11926:1)

fetch API returns the same error:

Code:

export const fetchPosts = () => {  
  return (dispatch, getState) => {
    return fetch(`${API_URL}/posts/all`)
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson)
      })
      .catch((error) => {
        console.error(error);
      });
  }
}

Error:
screen shot 2016-10-15 at 11 10 20 pm

Packages:

  "dependencies": {
    "axios": "^0.15.0",
    "classnames": "^2.2.5",
    "react": "15.3.2",
    "react-native": "0.35.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "redux-thunk": "^2.1.0"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-jest": "16.0.0",
    "babel-preset-react-native": "1.9.0",
    "jest": "16.0.1",
    "jest-react-native": "16.0.0",
    "react-test-renderer": "15.3.2"
  }

EDIT:
Solution for me was instead of using localhost:port for the API address, actually using an IP address of the server.

Содержание

  1. HTTP Fetch fails with «TypeError: Network request failed» => Resolved #32931
  2. Comments
  3. Description
  4. Problem description
  5. Solution
  6. Variant 1: using the certificates added manually to Android.
  7. Variant 2: using a certificate bundled with the app
  8. Important note (added on June 22, 2022)
  9. Version
  10. Output of npx react-native info
  11. Steps to reproduce
  12. Snack, code example, screenshot, or link to a repository
  13. «NETWORK ERROR» when making API call in react-native Android, while works in iOS #31045
  14. Comments
  15. Description
  16. React Native version:
  17. Steps To Reproduce
  18. Expected Results
  19. Snack, code example, screenshot, or link to a repository:
  20. Fetch not working for HTTP requests on Android #24408
  21. Comments
  22. 🐛 Bug Report
  23. To Reproduce
  24. Expected Behavior
  25. Code Example
  26. Environment
  27. Footer

HTTP Fetch fails with «TypeError: Network request failed» => Resolved #32931

Description

There are 83 issues opened and unanswered about network requests failing with this generic error.
The main causes of the pain are:

  1. Not getting an answer from the team
  2. The exception is far too generic and does not suggest the origin of the problem

Problem description

Using fetch to get/post on a HTTPS web server which is using a valid and trusted but not public CA.

  • Using Chrome and other apps the requests are always successful and without certificate problems

Sample code in react native:

Solution

Due to Android restrictions, a network_security_config configuration must be added to the application. It is an xml file that can be added by following these steps:

Variant 1: using the certificates added manually to Android.

In this case the CA must be visible in the User Certificates in the Android Settings. Try using them by opening a website that uses those certificates in Chrome to verify they are valid and correctly installed.

Content of the network_security_config.xml

The is the one giving access to the certificates installed manually.

Variant 2: using a certificate bundled with the app

You should export (using ssl) a pem certificate containing just the public key, naming it «ca» (no extension). Copy the certificate in the raw folder

Important note (added on June 22, 2022)

The local traffic (with the packager) must be unencrypted. For this reason the must contain the clearTrafficPermitted=true .
It is also important adding the ip addresses used from react-native when debugging otherwise the application will crash because of the android:networkSecurityConfig=»@xml/network_security_config» attribute. If you see the app crashing, take not of the ip used internally from react native and add it/them to this list. For example:

Requested fix: please never throw exceptions with a generic message, they are only a huge pain.

Version

Output of npx react-native info

info Fetching system and libraries information.
System:
OS: Windows 10 10.0.19044
CPU: (8) x64 Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz
Memory: 8.20 GB / 31.93 GB
Binaries:
Node: 16.13.0 — C:Program Filesnodejsnode.EXE
Yarn: 1.22.4 — C:Program Files (x86)Yarnbinyarn.CMD
npm: 8.1.3 — C:Program Filesnodejsnpm.CMD
Watchman: Not Found
SDKs:
Android SDK:
API Levels: 19, 23, 25, 26, 27, 28, 29, 30
Build Tools: 19.1.0, 21.1.2, 22.0.1, 23.0.1, 23.0.3, 26.0.2, 27.0.0, 28.0.0, 28.0.3, 29.0.2, 30.0.2
System Images: android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom
Android NDK: 22.1.7171670
Windows SDK:
AllowDevelopmentWithoutDevLicense: Enabled
AllowAllTrustedApps: Enabled
Versions: 10.0.10586.0, 10.0.14393.0, 10.0.15063.0, 10.0.16299.0, 10.0.17134.0, 10.0.17763.0, 10.0.18362.0, 10.0.19041.0
IDEs:
Android Studio: Version 2020.3.0.0 AI-203.7717.56.2031.7935034
Visual Studio: 17.1.32104.313 (Visual Studio Enterprise 2022), 16.11.32002.261 (Visual Studio Enterprise 2019)
Languages:
Java: 1.8.0_302
npmPackages:
@react-native-community/cli: Not Found
react: 17.0.2 => 17.0.2
react-native: 0.66.4 => 0.66.4
react-native-windows: Not Found
npmGlobalPackages:
react-native: Not Found

Steps to reproduce

Use the above code to make an HTTPS request to a website protected with certificates that are not public.
They will not succeed with a generic exception (as for the issue title)

Repeat the request to a public website and it will succeed.
The issue is the exception being too generic.

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

The text was updated successfully, but these errors were encountered:

Источник

«NETWORK ERROR» when making API call in react-native Android, while works in iOS #31045

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

Description

API calls not working in Android devices, while its working in iOS simulator and device

My network_security_config.xml

I’ve included this file (network_security_config.xml) in AndroidManifest.xml (android/app/src/main) too.

My FLIPPER_VERSION

Also I’ve commented out

API calls are successfully working in iOS devices but not working in android.

React Native version:

System:
OS: macOS 11.2.1
CPU: (8) x64 Apple M1
Memory: 33.83 MB / 8.00 GB
Shell: 5.8 — /bin/zsh
Binaries:
Node: 14.15.3 — /usr/local/bin/node
Yarn: Not Found
npm: 6.14.9 — /usr/local/bin/npm
Watchman: Not Found
Managers:
CocoaPods: 1.10.1 — /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
Android SDK:
API Levels: 29
Build Tools: 28.0.3, 29.0.2
System Images: android-29 | Intel x86 Atom_64
Android NDK: Not Found
IDEs:
Android Studio: 4.1 AI-201.8743.12.41.7042882
Xcode: 12.4/12D4e — /usr/bin/xcodebuild
Languages:
Java: 1.8.0_282 — /usr/bin/javac
Python: 2.7.16 — /usr/bin/python
npmPackages:
@react-native-community/cli: Not Found
react: ^16.13.1 => 16.14.0
react-native: ^0.63.2 => 0.63.4
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

Steps To Reproduce

Provide a detailed list of steps that reproduce the issue.

  1. Tried making API calls in Android.
  2. Its not working, its working in iOS devices.

Expected Results

Successful API Calls.

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

Please provide a Snack (https://snack.expo.io/), a link to a repository on GitHub, or provide a minimal code example that reproduces the problem.
You may provide a screenshot of the application if you think it is relevant to your bug report.
Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve

The text was updated successfully, but these errors were encountered:

Источник

Fetch not working for HTTP requests on Android #24408

🐛 Bug Report

When using fetch on http endpoints, the request raises a Network Request Fail error.
If works fine on https endpoints.

To Reproduce

use fetch with any http url.

Expected Behavior

The fetch function returns without throwing a Network Request Fail

Code Example

Environment

The text was updated successfully, but these errors were encountered:

Hey, I’ve had a similar problem, please make sure your request URL is HTTPS not HTTP as Android from new versions doesn’t allow HTTP

Unfortunately no. Best bet is debug js remotely option, moreover fetch related errors are not accurate at all for example recently I got a network request failure, then after hrs of self debugging I fixed my form data object

Try using this one. It worked for me.

Add the codes in your main AndroidManifest.xml :

Thanks @alexPimentel. It works for me

Thanks @alexPimentel for me it works even without tools:targetAPI=»28″.

Thanks @alexPimentel for me it works even without tools:targetAPI=»28″.

Thanks @alexPimentel for me it works even without tools:targetAPI=»28″.

Just had this issue and want to comment that this works
My env:
RN Version 0.60.4,
buildToolsVersion = «28.0.3»
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = «28.0.0»

«Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is «true». Apps that target API level 28 or higher default to «false».»

explains why this is a «sneaky regression».

I am using expo and i don’t have android and ios directory. How can i fix this issue.?
However, I am running it on lower version of API also but it is not working.

I have same problem

in my case everything resolve when I access my emulalator to network.
my android emulator didnt’t access to network.

I resolve from below.

this works for me

Try using this one. It worked for me.

Add the codes in your main AndroidManifest.xml :

Try using this one. It worked for me.

Add the codes in your main AndroidManifest.xml :

It’s Work . thank you.

I am facing the same issue in android release apk. React native version is 61.5. Tried with android:usesCleartextTraffic=»true»( tried with fetch and axios ,still not working). Also tried with http and https also, still no luck.
Everything works fine in debug mode.

@cjahfar1 Are you solve it?

Yes,. Actually «android:usesCleartextTraffic=»true»» fixed the issue. There were another error which was blocking the api calls and the error was swallowed since this error happens in saga function. Sorry for not updating here.

Yes,. Actually «android:usesCleartextTraffic=»true»» fixed the issue. There were another error which was blocking the api calls and the error was swallowed since this error happens in saga function. Sorry for not updating here.

I add «android:usesCleartextTraffic=»true»» but still i got

Request failed with status code 400

But it’s working fine in my Physical device

Yes,. Actually «android:usesCleartextTraffic=»true»» fixed the issue. There were another error which was blocking the api calls and the error was swallowed since this error happens in saga function. Sorry for not updating here.

I add «android:usesCleartextTraffic=»true»» but still i got

Request failed with status code 400

But it’s working fine in my Physical device

Status code 400 means, bad data. Double check the payload format. You are getting response 400, that means, API call is getting initiated.

Yes,. Actually «android:usesCleartextTraffic=»true»» fixed the issue. There were another error which was blocking the api calls and the error was swallowed since this error happens in saga function. Sorry for not updating here.

what is the error in saga function, and how to fix it man, plz help

Try using this one. It worked for me.

Add the codes in your main AndroidManifest.xml :

thanks. It works

Try using this one. It worked for me.
Add the codes in your main AndroidManifest.xml :

Yes,. Actually «android:usesCleartextTraffic=»true»» fixed the issue. There were another error which was blocking the api calls and the error was swallowed since this error happens in saga function. Sorry for not updating here.

Hi, but what was blocking the API calls?

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Hello Friends 👋,

Welcome To Infinitbility! ❤️

Getting error TypeError Network request failed in android, ios, or with SSL server then read all below cases.

In this article, we solve 3 cases of network request failed issue in react-native but your condition does not match with the below mention cases then comment below on the article.

Case 1: http url not working in android

if you are trying to call HTTP ( unsecured ) url then you have to add usesCleartextTraffic to your AndroidManifest.xml.

AndroidManifest.xml


<application
        ...
        android:usesCleartextTraffic="true"  <!-- add this line -->
    >
    ...
</application>

***Trying to call localhost api with diffrent port? ***

Replace localhost with your ipaddress v4

To know your ipv4

  • For windows users
  • For Mac or linux users

HTTP URL not working in ios

If you are trying to call an unsecure url from reac native ios.

you have to do below changes on your info.plist to allow unsecure url

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

HTTPS URL not working in android react native fetch

You are trying to call HTTP URL from react-native fetch but getting Network request failed to issue or in ios working fine then below the solution for you only.

This has to do with Android not trusting my SSL certificate. Apparently Android has some additional trust requirements on top of what web browsers require.

After figuring that out, the root cause ended up being my SSL Certificate uploaded to AWS didn’t have the correct intermediate cert which was fine in chrome, but not in android.

check your SSL certificate set up perfectly or not on https://www.digicert.com/help/.

when you get an error on DigiCert assign a task to your server administrator 😁.

Thanks for reading…

More From React Native Tutorial

Basics

1. Introduction To React Native

2. React Native Environment Setup using expo

3. React Native Environment Setup for windows

4. React Native Environment setup on Mac OS

5. React Native Environment setup on linux

6. React Native Project Structure

7. React Native State

8. React Native Props

9. React Native Styling

10. React Native Flexbox

11. React Native Text

12. React Native Textinput

13. React Native Commands

14. React Native ScrollView

Advances

1. React Native Dark Mode

2. React Native Fonts

3. React Native SQLite

4. React Native DatepickerAndroid

5. React native ScrollView scroll to position

6. How to align icon with text in react native

7. React Native Image

8. React Native Firebase Crashlytics

9. React Native Async Storage

10. React Native Share

Error & Issue Solution

1. Task :app:transformDexArchiveWithDexMergerForDebug FAILED In React Native

2. Expiring Daemon because JVM heap space is exhausted In React Native

3. Task :app:transformNativeLibsWithMergeJniLibsForDebug FAILED In React Native

4. Unable to determine the current character, it is not a string, number, array, or object in react native

5. App crashed immediately after install react native video or track player

6. how to delete SQLite database in android react native

7. React native material dropdown twice click issue

8. How to get the current route in react-navigation?

9. how to disable drawer on the drawer navigation screen?

10. Image not showing in ios 14 react native

11. React Native image picker launchimagelibrary on second time issue

12. how to open any link from react native render Html

13. Network request failed in react native fetch

14. React Native upload video example

Kevin Ilondo

If you are currently working on an app with React Native and you are using Laravel as your backend, you have probably encountered this problem.
And this article will help you solve this problem with just ONE SIMPLE TRICK.

SOMETIMES THIS PROBLEM IS CAUSED BY HOW YOU START YOUR LARAVEL APP

We all know how to start a Laravel server with the simple php artisan serve command and that’s the problem.
By starting your Laravel app like that it creates a link for your app which is localhost:8000 (the port may be different for you, it might be 3000, 8080 or anything else but we will use 8000 for this tutorial).
When making an HTTP Request with React Native, there is some kind of conflict because your Android app is run on an emulator which uses localhost too, and instead of sending the request to the localhost on your computer, it sends the request to the phone itself but with a different port and that is why you are getting this error.

THE TRICK THAT HELPED ME

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

D:xampphtdocsprojectslaravelblog>php artisan serve --host 10.10.10.2 --port="8000"
Laravel development server started: http://10.10.10.2:8000

Enter fullscreen mode

Exit fullscreen mode

Just start the server by giving an IP address and a port
It’s just that simple! Start your app as usual but don’t forget to give an IP address and a port, this will help you solve the Network Request Failed error.

NOTE: Replace 10.10.10.2 with your own IP Address, this is just an example.

//with axios
await axios.post('http://10.10.10.2:8000/api/user/login', data, headers)
    .then(res => {
      console.log(res.data)
    })
//with Fetch
await fetch('http://10.10.10.2:8000/api/user/login', {
method: "POST",
headers: headers //put your headers,
body: body //put the body here
})

Enter fullscreen mode

Exit fullscreen mode

And on your mobile app, make sure to use the correct URL in your request.
Make sure that CORS is enabled in your backend to avoid errors related to CORS. Next time I will make make a detailed post about how to enable it and how to solve issues related to CORS.

CONCLUSION

Start your Laravel app and enter your IP address and a port
Use the URL in your HTTP Request.
That’s it, I hope this post was useful to you and happy coding!

Answer by Landon Ortiz

Trying to fetch data from remote server via api.
Using fetch(https:url:port) to fetch the data. But every time android emulator as well as physical device gives network request failed. While I can access same url within browser of emulator.,what I found is when giving an empty form-data to fetch it fails as well with network request failed,The terminal result :
LOG [TypeError: Network request failed] ,Solve HTTP and HTTPS Network request failed issue in react native fetch

    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)})
    })
}`

Answer by Alexis Bentley

Developing with Windows OS/PHP built-in server/react-native Android on device:,check server local IP address (ipconfig), e.g. 172.16.0.10,run PHP built-in server with this specific IP instead of the localhost: php -S 172.16.0.10:8000 …,I´ve came across the following error.
At the moment I developing an Android App with React Native therefore I´m planning to use fetch for doing a post request for me.

Old header:

fetch(API_HOST, {
                method: 'POST',
                headers: {
                    Accept: 'application/json'
                },
                body: JSON.stringify(data),

Updated header:

fetch(config.API_HOST, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json'  // I added this line
                },
                body: JSON.stringify(data),

Answer by Ben Dunn

Use the following steps to configure your Android device to use Charles proxy:,This article describes the steps required to set up your Android device to proxy network requests through Charles, which is helpful for troubleshooting or debugging your implementation of Tealium for Android.,Setting up Charles to Proxy your Android Device,
Setting up Charles to Proxy your Android Device

<network-security-config>    <debug-overrides>      <trust-anchors>        <!-- Trust user added CAs while debuggable only -->       <certificates src="user" />      </trust-anchors>    </debug-overrides> </network-security-config>

Answer by Karsyn Weber

For more information, see Wi-Fi Network Request API for peer-to-peer
connectivity.,You may use this feature to capture a native monochrome image. A logical
multi-camera device may use a monochrome camera as a physical sub-camera to
achieve better low-light image quality.,For more information about this feature, see
Wi-Fi suggest.,For more information, see
Android changes for NDK developers.

Kotlin

val manager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
val channel = manager.initialize(this, mainLooper, null)

// prefer 5G band for this group
val config = WifiP2pConfig.Builder()
    .setNetworkName("networkName")
    .setPassphrase("passphrase")
    .enablePersistentMode(false)
    .setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_5GHZ)
    .build()

// create a non-persistent group on 5GHz
manager.createGroup(channel, config, null)

Answer by Mckenna Casey

node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:574:29 in setReadyState,node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:388:25 in __didCompleteResponse,Network request failed,node_modulesreact-nativeLibrariesvendoremitterEventEmitter.js:190:12 in emit

componentDidMount() {
const url = (Remote Http URL);
this.setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
this.setState(
{
loading: false,
error: res.error || null,
data1: res
},
()=> {
console.log(res);
}
);
})
.catch(error => {
this.setState({ error, loading: false }, () => {
console.log(error);
});
});
}

(Remote Http URL)

Answer by Skye Rosales

Let’s now set up an Android device to run our React Native projects. Go ahead and plug in your device via USB to your development machine.,It’s always a good idea to test your app on an actual device before releasing it to your users. This document will guide you through the necessary steps to run your React Native app on a device and to get it ready for production.,Open your React Native app on your device.,Repeat this step for the Tests target in your project.

$ adb devicesList of devices attachedemulator-5554 offline   # Google emulator14ed2fcc device         # Physical device

Answer by Renata Perez

App on physical iOS device stuck in ‘connecting…’ state,iOS physical device not showing up,Make sure only one device with React Native is running,Check your device isn’t on the list of known incompatibilities.

adb shell am start -n <APP_PACKAGE>/com.facebook.flipper.android.diagnostics.FlipperDiagnosticActivity

Answer by Kennedi Henry

If your code tries to open an HTTP connection to a host
on iOS or Android, a StateException is now thrown with
the following message:,If you would like to allow HTTP connections for Android debug
builds, you can add the following snippet to your $project_pathandroidappsrcdebugAndroidManifest.xml:,Starting with Android API 28 and iOS 9,
these platforms disable insecure HTTP connections by default.,You can allow insecure connections only to domains.
Specific IP addresses are not accepted as input.
This is in line with what platforms support. If you would
like to allow IP addresses, the only option is to allow
cleartext connections in your app.

Insecure HTTP is not allowed by platform: <host>

Answer by Miguel Church

Hello, really? It did work perfectly on my Android 9 device, that’s why I shared this. I didn’t know that it wasn’t working on Android 7. Have you tried it though?,From android 7 android not allowing unsecure HTTP request ,
We’re a place where coders share, stay up-to-date and grow their careers.
,
We’re a place where coders share, stay up-to-date and grow their careers.

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

D:xampphtdocsprojectslaravelblog>php artisan serve --host 10.10.10.2 --port="8000"
Laravel development server started: http://10.10.10.2:8000

Понравилась статья? Поделить с друзьями:
  • React hook form error message
  • React fetch error handling
  • React fetch cors error
  • React fetch catch error
  • React error page