首页 > 解决方案 > React Native https axios resquest 在 Android 而不是 iOS 上出现网络错误

问题描述

我正在构建我的本机应用程序并使用后端 URL 作为http://123.123.123.123:port/并且在开发过程中一切正常。但是当我构建我的应用程序并将其安装在 android 设备上时,它无法工作,我记得有人告诉我,android 默认情况下只允许 https 请求。所以我将 URL 更改为 Web 应用程序正在使用的 URL,即https://example.com/api/ ...(不是自签名 TSL 证书),现在 android 可以发送请求,但它们都返回为Network Errors (当在模拟器上构建和运行时),但它在 iOS 模拟器上运行良好。我是应用程序开发的新手,在网上找不到任何解决方案。也许我缺少一个选项?

我的 axios 设置,即发送请求:

const customAxios = axios.create({
        baseURL: baseURL,
        timeout: 6000,
    });

...

const response = await customAxios.post('/login', {
        email,
        password,
    });

错误堆栈:

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)
    at XMLHttpRequest.dispatchEvent (event-target-shim.js:818)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:574)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:388)
    at XMLHttpRequest.js:501
    at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
    at MessageQueue.__callFunction (MessageQueue.js:436)
    at MessageQueue.js:111
    at MessageQueue.__guard (MessageQueue.js:384)

https URL 适用于 ios 和 Web 应用程序

标签: javascriptandroidreact-nativeaxios

解决方案


在您的清单文件中添加android:usesCleartextTraffic="true"内部应用程序标记。

<application
  xmlns:tools="http://schemas.android.com/tools"
  tools:replace="android:allowBackup"
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:usesCleartextTraffic="true">...
</application>

推荐阅读