javascript - React Native fetch() Network Request Failed

ID : 20402

viewed : 29

Tags : javascriptreact-nativefetch-apijavascript

Top 5 Answer for javascript - React Native fetch() Network Request Failed

vote vote

95

The problem here is that iOS does not allow HTTP requests by default, only HTTPS. If you want to enable HTTP requests add this to your info.plist:

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

83

Not recommended to allow all domains for http. Make an exception for just the necessary domains.

Source: Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11

Add the following to the info.plist file of your app:

<key>NSAppTransportSecurity</key> <dict>   <key>NSExceptionDomains</key>   <dict>     <key>yourserver.com</key>     <dict>       <!--Include to allow subdomains-->       <key>NSIncludesSubdomains</key>       <true/>       <!--Include to allow HTTP requests-->       <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>       <true/>       <!--Include to specify minimum TLS version-->       <key>NSTemporaryExceptionMinimumTLSVersion</key>       <string>TLSv1.1</string>     </dict>   </dict> </dict> 
vote vote

72

I was using localhost for the address, which was obviously wrong. After replacing it with the IP address of the server (in the network that emulator is), it worked perfectly.

Edit

In Android Emulator, the address of the development machine is 10.0.2.2. More explanation here

For Genymotion, the address is 10.0.3.2. More info here

vote vote

64

I got the same issue on Android 9 because of the "http" and issue resolved by just adding android:usesCleartextTraffic="true" in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application   android:usesCleartextTraffic="true"  .......>  ....... </application> 

vote vote

58

For us it was because we were uploading a file and the RN filePicker did not give the proper mime type. It just gave us 'image' as the type. We needed to change it to 'image/jpg' to get the fetch to work.

form.append(uploadFileName, {   uri : localImage.full,   type: 'image/jpeg',   name: uploadFileName  }) 

Top 3 video Explaining javascript - React Native fetch() Network Request Failed

Related QUESTION?