【问题标题】:React native fetch/axios api calls always goes to catchReact 本机 fetch/axios api 调用总是去 catch
【发布时间】:2019-06-11 08:42:16
【问题描述】:

我尝试过同时使用 fetch 和 axios。但是这两个调用在我的 react-native 应用程序中都失败了。它总是进入 catch 函数。虽然从浏览器或 Postman 调用这个 api 工作正常。

axios.get('http://sahajdevapi.letsendorse.com')
.then(function (response) {
  console.warn("res 1: ", response);
}).catch(function (error) {
  console.warn("err 1: ", error);
});

我从 catch 函数得到的错误如下:

'err:', { [TypeError: Network request failed]
line: 24115,
column: 31,
sourceURL: 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false'}

【问题讨论】:

  • 您的网址无效!
  • 可以在浏览器上查看url:sahajdevapi.letsendorse.com
  • 这是网站老兄
  • 同意@HardikVirani ,请在邮递员中检查此网址,您将获得html回复:<h1 style='text-align: center; color: #ef5a20; margin: 40vh 0;'>SAHAJ</h1>
  • @AnkushRishi 任何类型的网络都会在邮递员检查任何网站时做出响应。假设检查一下:https://stackoverflow.com in postman

标签: api react-native axios fetch


【解决方案1】:

对于较新的版本,您需要为http 访问添加一些安全性。

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:name=".MainApplication"
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_launcher_round"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:ignore="GoogleAppIndexingWarning">

        <uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />

        <activity
            android:name=".MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

检查您需要添加清单标记toolsuses-library 的文件。

试试这个吧。

【讨论】:

  • 应用了清单中的更改,如您所述。但它仍然无法正常工作。它仍然给出同样的错误。
【解决方案2】:

由于 android VM 是一个模拟器 如果我们使用 localhost 那么它指向 android 模拟器系统的本地主机,而不是开发系统的 localhost。所以使用系统IP地址代替localhost

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多