Ionic 4 HTTP CORS Issue
Ionic 4 is a major upgrade to previous version of Ionic. One of the primary differences between Ionic 4 and its previous incarnations is that Ionic 4 uses web components, which are custom HTML elements written using web standards (as opposed to using a slap-on framework such as Angular).
Ionic 4 also makes a fundamental change in how the created app is rendered (I use rendered as apps are essentially HTML which is rendered using the native WebView control of the device's UI framework) in a device. While earlier versions used to refer to the top level index.html using file:// URI scheme, Ionic 4 internally spins up an HTTP server on localhost (yes for each app) and then loads the index.html through a standard HTTP request such as http://localhost:port/index.html.
Problem {#problem style="text-align: left;"}
I'm not sure what necessitated this change, but I reckon it probably had something to do with native API restrictions, which in turn was prompted by need for improved security. This, however, introduces a new (and common) problem. If your app interfaces with a remote server using HTTP requests, and you use the Angular HttpClient for making the requests, the remote server would typically reject the request as it would detect the request as coming from a different domain (domain would localhost) than the domain where it's hosted. This is due to CORS rules as set in the server configuration, which by default is set to reject all cross-domain requests.
Solution {#solution style="text-align: left;"}
You really have two options to solve this:
- If you own & manage the server, change its CORS setting to allow requests from any domain
- If you don't have control over the server or are reluctant to change the server's CORS setting, you have to switch to Ionic's native HTTP API to make HTTP requests.