Access-Control-Allow-Origin in phonegap

Ivan_nn2 picture Ivan_nn2 · May 19, 2014 · Viewed 9.9k times · Source

I decided to develop an app that uses a public API which provides time schedules for buses and subways in a city.

I decided to develop this app using HTML5 so that through the use of something like phonegap I would be able to deploy for multiple platforms.

During the development I discovered that I couldn't access the JSON response from the API due to the xmlhttprequest-cannot-load No 'Access-Control-Allow-Origin' header is present on the requested resource

So i decided to use a normal provider webspace as a bridge with a php function to which i send the request and that is able to get the response from that API service and send back to my HTML page the JSON result.

I have two questions for which also a starting page or a clue would be appreciated: 1) This problem of the Access-Control-Allow-Origin is something that would appear also if I developed the app in native code (java and ObjC)?

2) If the HTML5 and the javascript is compiled by phonegap I will be still unable to access that API service and I will still have the same problem and I will still have to use the php bridge?

Answer

jgillich picture jgillich · May 19, 2014

1) This problem of the Access-Control-Allow-Origin is something that would appear also if I developed the app in native code (java and ObjC)?

No, this is a security feature that only browsers implement.

2) If the HTML5 and the javascript is compiled by phonegap I will be still unable to access that API service and I will still have the same problem and I will still have to use the php bridge?

PhoneGap does set the correct headers that allow you to access all hosts. It is not able to overwrite or modify the headers that the responding server returns. Usually API endpoints DO set the correct headers, you should consider telling the API owners if they don't.