2017-10-14 133 views
1

我得到什麼,我認爲是在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白名單插件不能解決這個問題?

在此先感謝。已經花了很多時間在這個。

回答

0

我最近遇到了類似的問題。幾個月來,我的離子應用程序一直在運行,沒有問題,我突然開始在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一切都開始正常工作了。