【发布时间】:2016-07-14 14:20:05
【问题描述】:
我们目前正在使用 React-Native 开发一个移动项目。我们的应用程序依赖于 API。所以我们使用 React 的 fetch 方法从 API 中获取数据。我们的问题是 fetch 方法的工作方式基于 API 不同。当我们使用我们的 API 时,fetch 方法会抛出 Network request failed 错误。我们已经尝试了另一个公共 API 来测试,它运行良好,没有错误。
我在浏览器和 Postman 上测试了所有 API(测试 API),它们都正确显示了 JSON 响应。但是,我们在 fetch 方法上对其进行了测试,它的工作方式有所不同。这是一些代码sn-p来了解情况:
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库用于Web 和react-native 应用程序),但是有文档中有一些关于 cors 的问题:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
标签: json api reactjs react-native