【问题标题】:CORS redirect in CordovaCORS 在科尔多瓦重定向
【发布时间】:2017-09-30 07:03:23
【问题描述】:

我有一个 Cordova/Phonegap 应用程序试图通过 AJAX 获取一些文件。我收到以下错误:

XMLHttpRequest 无法加载 https://docs.google.com/uc?export=open&id=.... 从“https://docs.google.com/uc?export=open&id=...”重定向到“https://doc-xx-xx-docs.googleusercontent.com/docs/...?e=open”已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头请求的资源。起源 'null' 因此不允许访问。

我尝试将以下内容添加到config.xml

<access origin="*" />
<allow-navigation href="*" />
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />

还添加到index.html

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-eval' 'unsafe-inline' http: https:">

我正在使用cordova serve 访问浏览器中的应用程序。

我仍然遇到同样的错误。有什么想法吗?

【问题讨论】:

    标签: javascript ajax cordova cors


    【解决方案1】:

    假设您无法控制端点,您可能需要设置自己的 API 来执行此操作。

    例如,如果您在 php 中创建一个端点,您可以包含以下行:

     header('Access-Control-Allow-Origin: *');
    

    然后您的端点可以将请求转发到 Google 端点,该端点会将响应传递给您的 API,并且可以将响应传递给您的应用。

    我相信 Google 端点会接受来自其他服务器的请求,但如果源为空则不会。

    实际上,您需要确保您的请求来自 http:// 而不是 file:// URL。

    【讨论】:

    • php 中的端点?我说这是一个 Cordova 应用程序,我无法安装 php 代理。
    • 我知道这是一个 Cordova 应用程序。然而,来自 Cordova 的 XMLHttpRequest 将在发送时标头为空。您从中请求文件的 Google 端点不接受空源,因此我认为您可能需要在自己的服务器上使用自己的 API 作为发送请求的代理。
    • 在我的回答中添加了一些内容,希望能澄清我的观点。
    【解决方案2】:

    嗯,这些是你可以应用的浏览器平台和安卓平台的设置。

    config.xml

    <allow-navigation href="*://doc.google.com/*" />
    
    ...
    
    <platform name="android">
         ...
         <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
    </platform>
    

    network_security_config.xml

    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomain="true">doc.google.com</domain>
        </domain-config>
    </network-security-config>
    

    【讨论】:

      猜你喜欢
      • 2017-02-04
      • 2014-09-07
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2017-09-04
      相关资源
      最近更新 更多