当我使用react-native init (RN版本0.29.1)创建一个全新的项目,并在渲染方法中获取公共facebook演示电影API时,它抛出了一个网络请求失败。有一个非常无用的堆栈跟踪,我不能调试网络请求在chrome控制台。这是我发送的fetch:

fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });

当前回答

我使用localhost作为地址,这显然是错误的。在将其替换为服务器的IP地址(在仿真器所在的网络中)后,它可以完美地工作。

Edit

在Android Emulator中,开发机地址为10.0.2.2。更多解释在这里

对于Genymotion,地址是10.0.3.2。更多信息请点击这里

其他回答

如果你在REST api中使用docker,我的一个工作案例是将主机名:http://demo.test/api替换为机器ip地址:http://x.x.x.x/api。你可以通过检查你的无线网络的ipv4来获取IP。你的手机也应该有wifi。

这里的问题是iOS默认不允许HTTP请求,只允许HTTPS。如果你想启用HTTP请求,添加到你的info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

我在Android上遇到了这个问题

URL - localhost / authToken。Json -没有工作:(

URL - 10.106.105.103 / authToken。Json -没有工作:(

URL- http://10.106.105.103/authToken.json -工作:):D

说明—在Linux操作系统中使用ifconfig,在Windows操作系统中使用ipconfig查找机器的IpAddress

只是你有Fetch....的变化

fetch('http://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
        /*return responseJson.movies; */
        alert("result:"+JSON.stringify(responseJson))
        this.setState({
            dataSource:this.state.dataSource.cloneWithRows(responseJson)
        })
     }).catch((error) => {
         console.error(error);
     });

我在Android模拟器上遇到了同样的问题,在那里我试图使用有效的证书访问外部HTTPS URL。但是在react-native中获取URL失败了

'fetch error:', { [TypeError: Network request failed]
sourceURL: 'http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false' }

1)为了找出日志中的确切错误,我首先在应用程序上使用Cmd + M启用了“远程调试JS”

2)报告的错误为

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

3)我添加的URL的有效证书使用这种方法->步骤2

http://lpains.net/articles/2018/install-root-ca-in-android/

该证书被添加到User选项卡。

4)将属性android:networkSecurityConfig属性添加到AndroidManifest.xml

添加网络安全配置文件 res / xml / network_security_config.xml:

<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="user"/>
            <certificates src="system"/>
        </trust-anchors>
    </base-config>
</network-security-config>

这应该工作,并给你一个预期的回应。