Ionic v1 no 'Access-Control-Allow-Origin'

Hi to all,

I started a new app with ionic v1 using: cordova 8.0.0, ionic 3.20.0, cordova-android 7.0.0, cordova ios 4.5.4.
I use v1 because because i have no time to learn typescript now, i just developed 2 app with ionic v1.

All 3 apps share part of code, specifically the one for connecting to our servers, and I expect all of them to connect to the same servers without problems but…

The new app give me this error “Failed to load http://example.com: No ‘Access-control-Allow-Origin’ header is present on the request source…”

It happens with run command.

whitlist plugin is installed
is set in config.xml
In meta “Content-security-policy’ i tried also ''default-src *”

As i said, others apps have no problem to connect to same server but they use: cordova 7.0.1, ionic 1.7.16, cordova-android 6.1.0

I search and try many solution but nothing.

Thanks in advance.

It can depends of you platform : If you are using Chrome browser you can install this extension, it helped me to fix an API server connection error. You’ll have only to activate “Enable cross-origin ressource sharing” : https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=fr

<access origin="*" /> 
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />

can you add the above lines in the config.xml and try

@johnpaulcm @Youtch thanks for your reply.

@johnpaulcm I try your solution but nothing change.
@Youtch your solution is ok for ionic serve, but i don’t use it, i edited the question.

The server you are making a request to should provide an Access-Control-Allow-Origin header that allows the origin you are making a request from, see: https://enable-cors.org/server.html

You may experience different behaviour between apps as UIWebView doesn’t enforce CORS, whereas WKWebView does. There are ways to workaround CORS, but the best solution is just for the server to provide the appropriate header.

2 Likes

@joshmorony thanks for the input, for test i remove the cordova-plugin-ionic-webview (i have not look the documentation, it’s my fault) and the request works.

About the response header, often the simplest answer is the best, but I was stubborn on ‘it always works without…’

Just for curiosity, can u explain me links for workaround CORS (other than jsonp if exists)?

Since UIWebView does not enforce CORS you can downgrade to that from WKWebView, but then you are sacrificing application performance just to workaround a permission issue. Another approach is to use the native HTTP plugin to send requests - this proxies the requests through native code so there is no issue with requesting from different web origins.

Again, it’s much better to just get the CORS issue sorted server side, but if you had to it would be better to do something like using native HTTP than downgrading to UIWebView.

Thanks for the explanation!