简体   繁体   中英

CORS issues when emulating ionic app on iOS

I recently updated the ionic-cli and I am now trying to emulate an ionic app with the command ionic cordova emulate ios .

However, I am getting CORS errors with every api requests

Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

I found that the ionic docs say this about the above command

Like running cordova emulate directly, but also watches for changes in web assets and provides live-reload functionality with the --livereload option.

It seems like that command also starts a server, which would explain why the origin is localhost instead of file:// .

However, I tried emulating with cordova emulate ios , or building the app with ionic cordova build ios and running the output with the simulator, but I still get CORS errors.

Emulating on Android works fine and there is a proxy for running the app in the browser.

Any idea if I am on the right track and if there would be a way to emulate from file:// ? Would this problem persists when releasing the app to the App Store?

The problem with CORS on iOS actually did not come from the ionic-cli , but from the fact that I switched to using WKWebView from UIWebview .

This blog post explains more about WKWebView and why it is much better than its predecessor.

It also mentions this concerning 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.

So I enabled CORS on my api, and everything worked as before.

try creating an ionic proxy, adding this code to ionic.config.json

"proxies": [{
    "path": "/api",
    "proxyUrl": "http://your-server.com"
}]

and then call your server simply with http.get('/api')

If it still not working, try using the cordova http plugin instead of angular http.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM