By Alek Hurst


2016-07-17 07:42:42 8 Comments

When I create a brand new project using react-native init (RN version 0.29.1) and put a fetch in the render method to the public facebook demo movie API, it throws a Network Request Failed. There is a very useless stack trace and I can't debug network requests in the chrome console. Here is the fetch I'm sending:

fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });

16 comments

@Johannes Spohr 2019-03-07 09:39:07

I got the same issue on Android but I managed to find a solution for it. Android is blocking cleartext traffic (non-https-requests) since API Level 28 by default. However, react-native adds a network-security-config to the debug version (android/app/src/debug/res/xml/react_native_config.xml) which defines some domains (localhost, and the host IPs for AVD / Genymotion), which can be used without SSL in dev mode. You can add your domain there to allow http requests.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
    <domain includeSubdomains="true">dev.local</domain>
  </domain-config>
</network-security-config>

@Craciun Ciprian 2019-02-12 12:53:42

if you use docker for the REST api, a working case for me was to replace hostname: http://demo.test/api with the machine ip address: http://x.x.x.x/api . You can get the IP from checking what ipv4 you have on your wireless network. You should have also the wifi from phone on.

@Ocean Liu 2017-04-29 04:50:26

React Native Docs gives the answer for this.

Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project's Info.plist (or equivalent) file.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

React Native Docs -> Integration With Existing Apps -> Test your integration -> Add App Transport Security exception

@Cho Cho 2019-01-18 19:07:17

This worked for me, android uses a special type of IP address 10.0.2.2 then port number

import { Platform } from 'react-native';

export const baseUrl = Platform.OS === 'android' ?
    'http://10.0.2.2:3000/'
: 
'http://localhost:3000/';

@Preetam Keshari Nahak 2018-12-24 18:06:51

For Android devices, go to your project root folder and run the command:

adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]

e.g., adb reverse tcp:8088 tcp:8088

This will make your physical device(i.e. Android phone) listen to the localhost server running on your development machine (i.e. your computer) on address http://localhost:[your_own_server_port].

After that, you can directly use http:localhost:[your_port] /your_api in your react-native fetch() call.

@fangxing 2018-12-09 03:22:16

For Android user:

  1. Replace localhosts to a Lan IP addresses because when you run the project on an Android device, localhost is pointing to the Android device, instead of your computer, example: change http://localost to http://192.168.1.123

  2. If your request URL is HTTPS and your Android device is under a proxy, assume you have installed User-added CA(like burp suite's CA or Charles's CA) in your Android device, make sure your Android version is below Nougat(7.0), because: Changes to Trusted Certificate Authorities in Android Nougat

    User-added CAs
    Protection of all application data is a key goal of the Android application sandbox. Android Nougat changes how applications interact with user- and admin-supplied CAs. By default, apps that target API level 24 will—by design—not honor such CAs unless the app explicitly opts in. This safe-by-default setting reduces application attack surface and encourages consistent handling of network and file-based application data.

@Mahmoodvcs 2018-02-17 16:42:37

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

@Brandon Benefield 2018-07-19 07:35:14

Thank you. Probably the only response I've seen that works for android. Used my networks IP address and it works. eg http://<Network IP emulator connects to>:<port where API is served>/api/tasks

@Moucheg 2018-07-31 20:48:59

Don't forget the "http://" or else it won't work ... was wondering why it would work on postman but not with fetch

@NickJ 2018-11-27 07:04:04

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

@Ahmed Abumostafa 2018-12-24 04:34:33

after couple of hours you saved my day. Thanks

@Johhan Santana 2019-01-14 00:53:39

I wonder if there's a way to get the mime type automatically

@NickJ 2019-01-15 02:06:42

@JohhanSantana You could probably look at the raw image data and get it from the beginning, but the react native picker just came back 'image' for me.

@Akhila Antony 2018-08-29 05:31:16

Example:

return fetch('http://<your ip>')
  .then((response) => response.json())
  .then((responseJson) => {
    console.log(responseJson)
  })
  .catch((error) => {
    console.error(error);
  });

@Varun Kumar 2018-08-14 13:53:04

I was having this problem for Android-

URL- localhost/authToken.json - didn't work :(

URL- 10.106.105.103/authToken.json - didn't work :(

URL- http://10.106.105.103/authToken.json - worked :) :D

Note- Use ifconfig on Linux or ipconfig on Windows to find machine IpAddress

@Alek Hurst 2016-07-18 02:31:00

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>

@Marklar 2017-02-28 22:26:19

This answer worked for me. For others new to React Native, this file (info.plist) can also be edited through xcode: stackoverflow.com/a/38219454/1299792

@osuthorpe 2017-04-06 05:42:46

its not add but replace. The code is already in the info.plist, you need to replace the section or you will get an error.

@Vijay Sharma 2017-05-19 09:45:40

what about android? I am facing same issue in android as well.

@Zach Cook 2017-08-31 06:15:50

Exactly. Anyone have the answer for android?

@Jorge Wander Santana Ureña 2017-10-04 12:22:10

when i put that on ios/build/info.plist and run: react-native run-ios The ios/build/info.plist is overwritten and quit my changes What should i do ?

@kgosse 2017-10-31 00:15:55

@JorgeWanderSantanaUreña modify [your_project_folder_name]/ios/[your_project_folder_name]/In‌​‌​fo.plist

@JanithaR 2017-11-22 05:26:37

For Android give INTERNET permission

@masud_moni 2018-04-25 06:15:20

I have given INTERNET permission in the AndroidManifest.xml but yet I am having this issue. Any idea how to fix it? I would have torn all my hairs if I had any..grrr

@Sujit 2018-05-08 06:08:49

@masud_moni have you find any solution?

@masud_moni 2018-05-08 06:13:38

I have a partial solution. :( I just can send the request to the server, not my localhost.

@kurniawan26 2018-05-14 04:42:10

what about android ? Im facing this issue right now

@Sujit 2018-05-16 10:09:03

@kurniawan26 have you found any solution?

@kurniawan26 2018-05-17 02:35:52

@Sujit yup, I solved it. In my case it was Android emulator always sent charset: utf-8 on the header. so I need to ask my friend (backend) to changed the nginx setting to allow that additional header.

@Sujit 2018-05-17 13:40:58

@kurniawan26 For me the issue with Certificate.

@Aman Agarwal 2018-07-03 17:38:02

@Ивайло Янков 2018-05-17 16:26:22

I have similar problem. In my case requests to localhost was working and suddenly stopped. It turn out that the problem was that I was turn off my wifi on my android phone.

@Lavaraju 2016-10-15 10:07:39

Just you have Changes in Fetch....

fetch('http://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
        /*return responseJson.movies; */
        alert("result:"+JSON.stringify(responseJson))
        this.setState({
            dataSource:this.state.dataSource.cloneWithRows(responseJson)
        })
     }).catch((error) => {
         console.error(error);
     });

@Dmitry Maksakov 2017-07-18 10:08:19

The problem may be in server configuration.

Android 7.0 has a bug described here. Workaround proposed by Vicky Chijwani:

Configure your server to use the elliptic curve prime256v1. For example, in Nginx 1.10 you do this by setting ssl_ecdh_curve prime256v1;

@Shashwat 2017-06-06 13:49:10

For Android, you may have missed to add permission in AndroidManifest.xml Need to add the following permission.

<uses-permission android:name="android.permission.INTERNET" /> 

@masud_moni 2018-04-22 05:30:14

I already do have that even though I am getting that error, is there any other workaround?

@Lavi Avigdor 2016-07-24 18:46:09

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>

@arisalexis 2016-11-02 11:42:11

what about android?

@Marklar 2017-02-28 06:27:37

There seems to be multiple info.plist files in multiple directories in my React Native app. Any idea which folder contains the correct file to change?

@Stich 2017-04-05 12:09:53

@Marklar [your_project_folder_name]/ios/[your_project_folder_name]/In‌​fo.plist

@Aman Agarwal 2018-07-03 17:37:43

Related Questions

Sponsored Content

2 Answered Questions

2 Answered Questions

fetch data in react native from mlab

18 Answered Questions

[SOLVED] Abort Ajax requests using jQuery

2 Answered Questions

7 Answered Questions

2 Answered Questions

[SOLVED] React Native fetch() Network Request Failed for android?

  • 2018-01-06 18:42:05
  • durga patra
  • 2453 View
  • 3 Score
  • 2 Answer
  • Tags:   react-native

1 Answered Questions

0 Answered Questions

React native [TypeError: Network request failed]

0 Answered Questions

React native network request failed while fetching data

1 Answered Questions

[SOLVED] Load external json in react-native with fetch

Sponsored Content