IONIC 3 CORS 问题

Posted

技术标签:

【中文标题】IONIC 3 CORS 问题【英文标题】:IONIC 3 CORS ISSUE 【发布时间】:2018-03-28 09:09:49 【问题描述】:

我在尝试对 API 进行 GET 调用时遇到了 Ionic 3 的 CORS 问题。我正在使用 Ionic 本地服务器,在命令行中为实时服务器运行 ionic serve。

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

我尝试使用代理设置更新ionic.config.json,但这似乎不起作用..


  "name": "projectLeagueApp",
  "app_id": "47182aef",
  "type": "ionic-angular",
  "integrations": 
    "cordova": 
  ,
  "proxies": [
    
      "path":"/games",
      "proxyUrl": "https://api-2445582011268.apicast.io/games/"
    
  ]

我的数据服务

import  Injectable  from '@angular/core';
import  Http, Headers, RequestOptions  from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class DataProvider 

  headers = new Headers('user-key': '1234567890123');
  options = new RequestOptions (headers: this.headers); 
  limit: number = 50;

  constructor(public http: Http) 
    console.log('Hello DataProvider Provider');
  

  getGames(genre, offset_num) 

    let genre_id = genre;
    let offset = offset_num;

    return this.http.get('https://api-2445582011268.apicast.io/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
  


我正在尝试调用这个 api

请求网址

https://api-2445582011268.apicast.io
HEADERS
Key Value
user-key    YOUR_KEY
Accept  application/json

主要问题 我的电话失败了。如何为此问题创建代理?

【问题讨论】:

尝试将http.get请求中的url改为/games。代理会将其替换为真实的。 复制:***.com/questions/41861105/… Handling CORS Issues in Ionic的可能重复 【参考方案1】:

要解决此问题,请更改以下行

ionic.config.json


  "name": "projectLeagueApp",
  "app_id": "47182aef",
  "type": "ionic-angular",
  "integrations": 
    "cordova": 
  ,
  "proxies": [
    
      "path":"/games",
      "proxyUrl": "https://api-2445582011268.apicast.io/games"
    
  ]

您必须删除“proxyUrl”末尾的“/”。

我的数据服务

return this.http.get('/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)

在 http 调用中,url 应该以“/games”开头。 '/games' 因为 ionic 会将 http://localhost:<port>/games 代理到 https://api-2445582011268.apicast.io/games

请在您的应用程序中使用上述方法进行外部 GET 和 POST 调用。

谢谢。

【讨论】:

很高兴为您提供帮助。 @ChrisSimmons 请对此答案投赞成票,以便有类似查询的开发人员可以从中获得解决方案。 @AlvinChettiar 和 Chris Sommons,非常感谢这个完整的例子。这很有意义,也解决了我的问题。在我看到这个完整的例子之前,官方网站上的文档毫无意义。再次感谢。 只是一个友好的提示 - 在对 ionic.config.js 进行更改后,请记住 ionic serveionic lab - 如果没有“重新启动”,它将不会像其他代码更改一样生效:) @Grant,你的意思是再次停止和运行离子服务?我正在执行类似的步骤,但我仍然无法让代理正常工作。 @Emulic 正确 - 只需 CMD+C 或 CTRL+C 并取消正在运行的服务,确保您的代理更改已完成,然后再次运行 ionic serve 或 ionic lab。将其视为必须提交的别名,并且必须重新启动服务才能使用它。【参考方案2】:

如果您想在 Chrome 中进行测试,只需安装 chrome 扩展 Allow control origin 快速简便的方法

【讨论】:

【参考方案3】:

要在开发环境中测试,您可以在disable-web-security 模式下运行谷歌浏览器。

要遵循的步骤(在 Windows 上)

Windows键+R打开运行窗口。 输入/输入以下命令并按Enter键。

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

要遵循的步骤(在 Ubuntu 上)

在运行/执行之前杀死所有 chrome.exe 实例。

chromium-browser --disable-web-security --user-data-dir="[some directory here]"

Chrome 48 之前

chromium-browser --disable-web-security

要遵循的步骤(在 Mac 上)

在终端中运行以下命令。

open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security

【讨论】:

【参考方案4】:

代理功能需要您引用本地服务器。在您的 GET 请求中,您仍然指向远程 API。如果您将代码更改为 this.http.get('/games/...',它应该会开始运行,因为请求将转到 http://localhost:8100/games...,“代理”选项将捕获并传递给您提供的 URL。

您可能还只需将https://api-2445582011268.apicast.io 放入proxyUrl 字段。我认为其余的路径是直通的。

【讨论】:

嘿,杰夫,我按照你的要求做了。我将 proxyUrl 更改为 'api-2445582011268.apicast.io' 并且不再收到 CORS 问题。我现在有另一个问题。我收到一个新错误 - “运行时错误,位置 0 处 JSON 中的意外令牌 H”。我不确定为什么会收到此错误。 通过 chrome 开发工具网络选项卡查看您的请求。 HTTP 响应代码是什么?您可能会在那里看到更多信息。此外,不确定您是否在控制台中看到任何表明代理正在处理请求的内容。也许那里有更多信息。此外,我建议使用 ARC 或 Postman 或一些 REST 客户端来访问您的代理服务,其配置类似于您在网络选项卡中看到的内容。在那里调试 API 调用可能更容易。【参考方案5】:

当我从 Play 商店更新 Android System Webview 时,我的 CORS 问题得到了FIXED。 我尝试了 Cordova-Advance-HTTP 插件,但我的 PUT 请求无法使用 Cordova-Advance-HTTP 插件运行

更新后 Android System Webview 我使用了之前使用的 HTTP Client 插件。在 CORS 问题上更新 Android System Webview 帮助我

【讨论】:

【参考方案6】:
```
export function getAuthHttp(http: Http, options: RequestOptions) 
  console.log("token",storage.get('id_token'));
  return new AuthHttp(new AuthConfig(
          headerName: 'Authorization',
          headerPrefix: 'bearer',          
          tokenName: 'id_token',
          tokenGetter: (() => storage.get('id_token')),
          noJwtError: true,    
          //globalHeaders: ['Accept': 'application/json'],
          globalHeaders: ['Content-Type':'application/json',"Access-Control-Allow-Origin": "*"],
         
        ), http, options);

```

【讨论】:

【参考方案7】:

在浏览器中调试时,您可以通过使用 CORS 扩展或禁用 Chrome 的安全性来处理 CORS。 但是当您在服务器端的应用程序中调试时需要处理 CORS,我正在使用 woo-commerce API,所以我将其编辑如下->

1.Plugins->editor->woocomerceapi

紧接着

<?php**
header(“Access-Control-Allow-Origin: *”);   

2.更新文件

【讨论】:

以上是关于IONIC 3 CORS 问题的主要内容,如果未能解决你的问题,请参考以下文章

CORS Ionic 3 发布请求

在 ionic 4 上使用 Angular 7 帖子时出现 Cors 策略错误

移动设备上的 Ionic 4 CORS 问题

如何解决 Ionic2 中的 CORS 问题和 JSONP 问题

Ionic CLI 6.13.0 上的 CORS 问题

本地主机和设备上的 Ionic 的 CORS 问题[关闭]