离子3在iPhone模拟器CORS问题

离子3在iPhone模拟器CORS问题

问题描述:

我得到什么,我认为是在iPhone模拟器版本CORS问题SimulatorApp-829.6 /的Xcode 9.0离子3在iPhone模拟器CORS问题

我建立了一个ionic3应用瓦特/科尔多瓦,并且可以在运行浏览器使用代理。但是,当我在SIM或手机上运行它时,它不会针对远程http呼叫进行身份验证。

所以我添加科尔多瓦调试器和调试的Xcode的控制台:

这是HTTP错误对象:

{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}

这是我在离子应用程序执行代码(在浏览器中的作品)

let headers = new Headers(); 
 
    headers.append('Content-Type', 'application/json'); 
 
    headers.append('Authorization', 'Basic ' + this.base64Service.encode(id + ':' + pw)); 
 
    headers.append('Access-Control-Allow-Origin', '*'); 
 
    
 

 
    return this.http.get('http://myserver.com/api/v1/authenticate', {headers: headers}).map(res => res.json());

我真的很困惑,因为两件事情:

1)我已经安装了科尔多瓦白名单的插件和之前已经成功对远程服务器。不知道这是怎么回事

2)如果我使用Safari开发>模拟器,并连接到在模拟器中运行的应用程序也给出了这样的错误:

Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. 

XMLHttpRequest cannot load http://myserver.com/api/v1/authenticate. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. 

你怎么可以在SIM获得CORS问题或实际设备?我认为这些资源都是基于file://的。另外,为什么Cordova白名单插件不能解决这个问题?

在此先感谢。已经花了很多时间在这个。

我最近遇到了类似的问题。几个月来,我的离子应用程序一直在运行,没有问题,我突然开始在iOS上收到CORS错误。

问题是我改用WKWebViewUIWebview

This blog post解释了更多关于WKWebView,以及它为什么比它的前身更好。

它也提到了这一点关于CORS:

UIWebview, or the older webview in iOS, never actually enforced CORS, but WKWebView does and does not provide a way to disable it. To address this, you need to implement CORS correctly and add the following entry:

Origin: http://localhost:8080

IF this is not possible (you do not own the API), a workaround can be to use the native HTTP plugin, @ionic-native/http.

所以这两个解决方案:

  1. 如果你拥有你所使用的API,使得它CORS
  2. 如果你可以” t修改api,你可以使用Ionic Native Http

我去了第一个和e一切都开始正常工作了。