iOS 上的 React Native Axios 请求返回“网络错误”

问题描述 投票:0回答:5

我创建了一个 RN 项目(没有 Expo)并设置了我的 API 服务。我正在使用 dummyapi.io 来获取虚拟发布数据,这是一个 HTTPS 请求。我不断收到来自 Axios 的“网络错误”,当我查看错误详细信息时,我看到以下消息:

"_response": "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “dummyapi.io” which could put your confidential information at risk."

Android 上一切正常,所以我认为这与 Apple 疯狂的安全规则有关。

我尝试在 Info.plist 上添加以下内容,但没有用:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.dummyapi.io</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

为了进一步解释我的问题,对“google.com”的 GET 调用可以工作,但“jsonplaceholder.typicode.com”则不行。我将不胜感激有关此问题的任何帮助,我现在非常绝望。

React Native Version: 0.66.4
React Version: 17.0.2
Axios Version: 0.24.0
reactjs react-native networking https axios
5个回答
4
投票

您对 IOS 安全规则的看法是正确的。将以下内容添加到

plist.info
将禁用所有应用程序传输安全限制,并应允许您通过 HTTP 连接:

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

否则,您将必须生成根 CA 证书,并将其安装在您的设备上。

以下是如何生成根证书并使用它来生成自签名证书:https://www.ibm.com/docs/en/runbook-automation?topic=certificate-generate-root-ca-key
以下是如何在 IOS 设备上安装它:https://medium.com/collaborne-engineering/self-signed-certificates-in-ios-apps-ff489bf8b96e

此问题与:https://stackoverflow.com/a/38427829/17922074


4
投票

要解决此问题,请按照以下步骤操作:

1- 前往

info.plist

2-接下来找到钥匙

<key>NSAppTransportSecurity</key> 

3- 在按键的

<dict></dict>
内添加以下代码:

 <key>NSAllowsArbitraryLoads</key>
<true/>

0
投票

我明白了,感谢这个问题!显然,在进行任何 API 调用之前,应用程序需要完全启动并运行,这导致 App.js 中出现类似这样的内容

import {AppState} from 'react-native';

const App = () => {
  return (
    {AppState.currentState === 'active' && <Navigation />}
  );
};

希望这对遇到类似问题的人有所帮助!


0
投票

删除模拟器并创建一个新模拟器,成功了! (尝试使用不同的模拟器)


0
投票
    Open Info.plist in your ios directory
  and add this to you file

    <key>NSAppTransportSecurity</key>
        <dict>
            <key>NSAllowsArbitraryLoads</key>
            <true/>
            <key>NSExceptionDomains</key>
            <dict>
                <key>localhost</key>
                <dict>
                    <key>NSExceptionAllowsInsecureHTTPLoads</key>
                    <true/>
                </dict>
            </dict>
        </dict>
    
    
    This works for me 
© www.soinside.com 2019 - 2024. All rights reserved.