cordovaionic3ionic-cli

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?


Solution

  • 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.