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