현재 모바일 프로젝트를 개발하기 위해 React-Native를 사용하고 있습니다. 우리의 애플 리케이션은 API에 달려있다. 따라서 React의 fetch 메소드를 사용하여 API에서 데이터를 가져옵니다. 문제는 fetch 메소드가 API에 따라 다르게 작동한다는 것입니다. API를 사용할 때 fetch 메소드가 네트워크 요청을 실패했습니다 오류. 테스트 할 다른 공개 API를 시도했지만 완벽하게 작동합니다. 오류가 없습니다.React-Native Fetch API는 API에 따라 다르게 작동합니다.
브라우저 및 Postman (테스팅 API)에서 모든 API를 테스트했는데 모두 JSON 응답을 제대로 보여줍니다. 그러나 fetch 메소드에서 테스트합니다. 다르게 작동합니다. 다음은 상황을 이해할 수있는 코드 스 니펫입니다.
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>
);
}
}
당신은'CORS'에 문제가 있다고 가정합니다.'fetch'가 어떻게 작동하는지 잘 모르겠습니다. (웹 프로젝트와 반응 네이티브 애플 리케이션 모두에'superagent' 라이브러리를 사용합니다.)하지만, cors https : // developer.mozilla.org/ko-US/docs/Web/API/Fetch_API/Using_Fetch' –