【问题标题】:React-Native Fetch API Works Differently Based On APIsReact-Native Fetch API 的工作方式基于 API 不同
【发布时间】: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


【解决方案1】:

该问题围绕 iOS 中的应用程序传输安全策略展开。 randomuser API 是 SSL,而其他的不是。

在 XCode 项目的 info.plist 文件中,在 NSAppTransportSecurity 字典下添加键 NSAllowsArbitraryLoads,其值为 YES。这将允许您的其他端点成功获取。

【讨论】:

  • Brice,感谢您的解决方案。我建议你编辑你的答案。这是正确的,但是 info.plist 参数应该根据 stackoverflow.com/a/31807139/1175235 更新。根据该答案, fetch 方法可以完美运行。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
相关资源
最近更新 更多