【问题标题】:CORS error on XHR request but only on android (iOS works fine...)XHR 请求上的 CORS 错误,但仅在 android 上(iOS 工作正常......)
【发布时间】:2022-02-09 06:02:29
【问题描述】:

我有一个使用 Capacitor 制作的 android/iOS 应用程序,它提供一个 html 文件,向我的服务器发出 XHR 请求。

它在 iOS 模拟器/设备上运行良好,但在 android 模拟器上运行良好。我收到以下错误

File: http://example.com/ - Line 0 - Msg: Access to XMLHttpRequest at 'https://example.com/api/users/me?_=1644242401129' from origin 'http://example.com' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我确实有一个Access-Control-Allow-Origin 设置。证明它可以在 iOS 上运行,允许以下来源:

capacitor://example.com

但在 android 上,看起来使用的原点是 http://example.com,正如错误所说。

我确实在我的标题“Access-Control-Allow-Origin”上允许了这个 url,但它仍然失败并给我同样的错误。


    $allowed_domains = [
        'https://example.com',
        'http://example.com',
        'capacitor://example.com', //iOS working fine       
    ];

    if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {

        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Credentials: true');
    }

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

       header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
       header('Access-Control-Allow-Headers: origin, content-type, accept, API');
       header('content-type: application/json; charset=utf-8');
       http_response_code(200);
       exit;
    }

【问题讨论】:

    标签: android ios cors xmlhttprequest capacitor


    【解决方案1】:

    通过删除capacitor.config.json中的以下条目解决了这个问题

      "server": {
        "hostname": "example.com"
      },
    

    这将我的来源更改为 Android 的 http://localhost 和 iOS 的 capacitor://localhost

    在我的服务器上允许两个来源,现在它可以在 android 上运行,但不能在 iOS 上运行。 Cookie 在 iOS 上不再随我的 XHR 请求一起发送(在 android 上运行良好)。

    所以我想解决方案是使用服务器主机名在 iOS 上构建,而在没有它的情况下在 android 上构建。太好了..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 2019-12-13
      • 2014-12-22
      • 2011-06-21
      • 2014-06-08
      • 1970-01-01
      • 2018-08-01
      • 2015-09-16
      相关资源
      最近更新 更多