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>
    );
  }
}
1
  • 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 Commented Jul 14, 2016 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 stackoverflow.com/a/31807139/1175235 . According that answer, fetch method works perfectly. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.