Hey all! I’m trying to run my Ionic 3 app on my phone. I seem to be having some trouble connecting to an API using HTTP requests. I’m running into the infamous CORS problem. I’ve tried almost everything I read around the net and nothing seems to be working; In browser using ionic serve or on mobile using ionic cordova run android --livereload.
Hey Sujan!
Thanks for your answer. Taking another look at the error it says that there is no ‘Access-Control-Allow-Origin’ header on the requested resources. From what I personally understand that means the API I’m calling is missing the above header. Is that correct?
But if you mean to say that I should include the header in my request payload, then I’ve already attempted to do so as such:
No, the API has to respond with that header - it allows a specific Origin (in this case the one of the Ionic app) to get the data the request returns. Otherwise the “browser” (the webview in this case) will not forward the result to your app and throw this error message.
Many APIs allow you to set that value. If not, you will have to find a workaround (like a proxy on your server that does the actual request, adds the header and returns that to your app).
Unfortunately, I do not have control over this API whatsoever; I’m simply calling data from it.
I was able to make these calls via a NodeJS project, but the attempt was fruitless via Ionic.
Also as I mentioned in the first post, I did try to use a proxy to fix this problem but it didn’t affect the Ionic app’s behavior.
NodeJS doesn’t work in the context of a browser with the security restrictions this environment adds - so this is not an issue there. The proxy you tried to use is a different thing than what I suggested and doesn’t really help here.
Ah I did re-read what you posted and I’m not too excited about it
Payload path:
Ionic App --> My Server (with proxy) --> API
And the response would be take the same road back to the app. Correct?
Doesn’t seem very… ‘Efficient’ might be the word? Is there no other way to do it?
Ionic’s http is Angular’s http which is in TS/JS - native HTTP is… native code. Outside the context of the webview, so outside of these security considerations (at the cost of performance and complexity of course).