Ionic 无法打开 Cors

2023-12-30

我正在尝试从 ionic android 应用程序中的实时服务器获取 API 数据,但它返回此错误:

Access to XMLHttpRequest at 'https://example.com/api/categories/' from origin 'http://192.168.43.71:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

服务器设置

现在我使用 Laravel 作为实时服务器,它提供了 API,这是我在 Laravel 应用程序中设置 CORS 的方式:

/bootstrap/app.php

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Allow-Headers: *');
    // rest of the file

由于我上面的设置,我在 CORS 测试仪上得到了这个结果

离子设置

因此,我一直在阅读如何解决这个问题,并遇到了很多类似的解决方案,这就是我添加到我的解决方案中的内容ionic.config.json file

"proxies": [
    {
      "path": "/api/*",
      "proxyUrl": "https://example.com/api/"
    }
  ]

获取请求(离子服务)

这是我请求 get 方法的方式

apiUrl = 'https://example.com/api/categories/';
  constructor(private http: HttpClient) { }

  getCategories(): Observable<any> {
    return this.http.get(`${this.apiUrl}`).pipe(
      map(categories => categories)
    );
  }

知道我还应该做什么来解决这个问题吗?


SOLVED

谢谢Stephen Romero为了指出这个解决方案的重要部分,

根据斯蒂芬的回答,我将此代码添加到我的函数中:

const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'application/json, text/plain',
        'Content-Type': 'application/json'
      })
    };

并在我的 get 请求中使用它,例如:

return this.http.get(`${this.apiUrl}`, httpOptions).pipe(

现在我使用的 for header 权限(已安装)这个包 https://github.com/barryvdh/laravel-cors在我的 laravel 应用程序上,并将配置文件设置为以下代码:

return [
    /*
    |--------------------------------------------------------------------------
    | Laravel CORS
    |--------------------------------------------------------------------------
    |
    | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
    | to accept any value.
    |
    */

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['GET', 'OPTIONS'],
    'exposedHeaders' => [],
    'maxAge' => 0,

];

对于那些不使用 Laravel 的人

像这样设置标题:

if($request_method = 'GET'){
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, OPTIONS');
    header('Access-Control-Allow-Headers: Authorization, Expires, Pragma, DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range');
    header("Access-Control-Expose-Headers: *");
}

这个标题中最重要的部分是Access-Control-Allow-Headers部分,如果你只是使用*这是行不通的!您需要设置标题名称。

希望能帮助到你。

Update

为了避免错误忘记提及301你需要删除/从你的 api url 末尾开始。

// my api (before)
https://example.com/api/categories/

//changed to
https://example.com/api/categories
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ionic 无法打开 Cors 的相关文章

随机推荐