$http doesn't work on ionic serve due to CORS!

I was trying to play with simple $http call to my external server (apis and other stuff to load/update data).
As i’m developping i’m using ionic serve

$http is not working on my firefox or chrome due to CORS protection !
I lost about 2 hours to find it and the ionic blog post helped me

I’ve created my proxies in ionic.project and constant on app.js.

I’ve not used the gulp way to replace “dev” version and “prod” version. Instead i’m using a simple if which work on dev and prod.

var url  = API_PROD_URLS.'/myUrlsParams';
if (!window.cordova) // if current device is not a real one (ionic serve or ionic lab)
       url  = API_DEV_URLS.'/myUrlsParams';
$http.get(url) [...]

And everything is working like a charm.

i simply start my chrome with --disable-web-security flag and it is done… no need to define proxies or anything else.

@nraboy posted a little article about it for the main browsers safari, chrome and firefox:

I’ve tried it first but it was not working on my mac and if i forgot to re-enable cors protection i could be like “naked” on the web, so i prefered using proxies.

Other pros of using proxies is that i can change it quickly if my api urls change (for QA and PROD for example) and i can do it in only a single place. (using only constants in app.js could also do the tricks but i used the “official” way described on the ionic blog post as a gentle learner :slight_smile: )

1 Like

ionic team had made a blog post on this cors purpose.
You can look at it here