0

We are currently using React-Native to develop a mobile project. Our app depends on an API. So we use React's fetch method to get data from the API. Our issue is that the fetch method works differently based on APIs. When we use our API, fetch method throws Network request failed error. We have tried another public API to test, It works perfectly, no error.

I tested all APIs on browser and Postman (testing API), all of them shows JSON response properly. However, we test it on fetch method, it works differently. Here's some code snippet to understand the situation:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  AlertIOS
} from 'react-native';

class Test extends Component {
  constructor() {
    super();

    state = {
      airports: []
    }
  }

  onAfterLoad = (data) => {
    AlertIOS.alert(
      "Fetched Successfully"
    );
    this.setState({
      airports: data.airports
    });
  }

  componentWillMount() {
    // Fails
    let api1 = 'http://kolaybilet.webridge.co/api/v1/airports/ist/';
    // Fails
    let api2 = 'http://jsonplaceholder.typicode.com/posts/1/';
    // Works
    let api3 = 'https://randomuser.me/api/';

    fetch(api1)
      .then((r) => {
        return r.json();
      })
      .then(this.onAfterLoad)
      .catch((e) => {
        AlertIOS.alert("An Error Has Occurred!", e.message);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
      </View>
    );
  }
}
Ali Emre Çakmakoğlu
  • 864
  • 2
  • 12
  • 24
  • I assume you have problems with `CORS`, I do not know well how `fetch` works (in my projects I use `superagent` library both for web and react-native apps), but there are some issues about cors in documentation: `https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch` – Andrea Korinski Jul 14 '16 at 14:32

1 Answers1

3

The issue centers around the App Transport Security policy in iOS. The randomuser API is SSL while the others are not.

In your XCode project's info.plist file, add the key NSAllowsArbitraryLoads under the NSAppTransportSecurity dictionary with a value of YES. This will allow your other endpoints to be successfully fetched.

Ali Emre Çakmakoğlu
  • 864
  • 2
  • 12
  • 24
Brice Mason
  • 686
  • 5
  • 8
  • Brice, I appreciate for your solution. I suggested you to edit your answer. It is correct, however the info.plist parameter should be updated based on http://stackoverflow.com/a/31807139/1175235 . According that answer, fetch method works perfectly. Thanks a lot. – Ali Emre Çakmakoğlu Jul 14 '16 at 23:32