Important! The only purpose of this post is to avoid having CORS issues while local testing, this is not for production servers !
If you want to avoid having CORS issues with Ionic this is the fastest and easiest way:
1. Create a file called proxy.conf.json at the same level as the angular.json file and add the next in the content
{
"/custom-path/*": {
"target": "https://mydomain.com",
"changeOrigin": true,
"secure": false,
"pathRewrite": {"^/custom-path" : ""}
}
}
2. We have to update angular.json file to load proxy configuration for the ionic serve command:
...
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build",
"proxyConfig": "./proxy.conf.json"
},
3. Update the API calls, in my case I have a service like this:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class Api{
constructor(public http: HttpClient) {}
getUserInfo(){
return this.http.get('/custom-path/api/users')
}
}
Tip: From the above URL, '/custom-part/' will be replaced with "http://mydomain.com", so the URL will be: "http://mydomain.com/api/users"
That solved the CORS issue for me, after that I was able to call API's and the browser stop complaining.
If you're still having CORS issue, you can try to call ionic serve command like this:
ionic serve -- --proxy-config ./proxy.conf.json
Important! Notice the extra dashes '--', do not omit those