【问题标题】:CORS issue with Ionic on localhost and on device [closed]本地主机和设备上的 Ionic 的 CORS 问题[关闭]
【发布时间】:2020-12-22 22:13:54
【问题描述】:

我有一个 Ionic 项目正在对我在 Azure 中的数据库和一个外部 API 进行 API 调用。我不断收到 CORS 错误:

错误请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://localhost:8100'。

我在网上看到这可能发生在浏览器中,但问题是当我通过 apk 安装应用程序时也遇到了这个问题。此外,最奇怪的是我大约有 10% 的时间会出现这个错误。这意味着我可以在一分钟内执行所有的 GET 和 POST 请求,然后在下一分钟我不断收到这些错误。我不知道这个错误是如何只能偶尔触发的,所以如果有人知道如何解决这个问题会很棒。

【问题讨论】:

    标签: angular ionic-framework cors


    【解决方案1】:

    您必须在您的原生 android 项目 android/app/src/main/res/xml 目录中创建一个 network_security_config.xml 文件,其中包含以下内容:

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
          <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">localhost</domain>
          </domain-config>
    </network-security-config>
    

    然后在您的 AndroidManifest.xml 文件中添加:android:networkSecurityConfig="@xml/network_security_config,使其看起来像这样:

    <application 
                 android:networkSecurityConfig="@xml/network_security_config" 
                 android:allowBackup="true" 
                 android:icon="@mipmap/ic_launcher" 
                 android:label="@string/app_name" 
                 android:roundIcon="@mipmap/ic_launcher_round" 
                 android:supportsRtl="true" 
                 android:theme="@style/AppTheme">
    

    或者,您可以使用平台原生 HTTP 库,而不是使用 HTTPClient (angular),您可以在此处找到:https://github.com/capacitor-community/http 如果您使用的是 Capacitor,或者https://ionicframework.com/docs/native/http 如果您使用的是 Cordova,您不会不再有 CORS 问题。

    【讨论】:

    • 成功了!谢谢!
    • 不客气!!
    猜你喜欢
    • 2018-07-09
    • 2019-03-18
    • 2018-08-13
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2011-05-30
    相关资源
    最近更新 更多