OpendataCH / Transport

Swiss public transport API
http://transport.opendata.ch/
MIT License
241 stars 50 forks source link

Allow client-side integration through JSONP and/or CORS #82

Closed marcelstoer closed 11 years ago

marcelstoer commented 11 years ago

I'd like to be able to integrate the API right into a web client. We're working on a Sencha Touch application that has no server component. Still, we'd like to use the transport API.

Due to the same origin policy the only two options right now are either to run a reverse proxy which forwards requests to http://transport.opendata.ch/v1 or to run our own transport server (which we do now).

Request: allow for client-side integration (i.e. AJAX) of the transport API through JSONP and/or CORS.

http://enable-cors.org/ http://nelm.io/blog/2011/11/cors-with-sencha-touch/

christianmeichtry commented 11 years ago

I would like to see this feature too.

fabian commented 11 years ago

CORS has been enabled since the beginning. Are you experiencing problems with client-side integration anyways?

GET /v1/locations?query=Basel HTTP/1.1
HTTP/1.0 200 OK
Access-Control-Allow-Origin: *
marcelstoer commented 11 years ago

Since it isn't documented that you support CORS I assumed you wouldn't.

However, there's a problem indeed with your current setup. Sencha/jQuery and most likely other JS libs set a custom X_REQUESTED_WITH header on the XHR object. This in turn causes the browser/XHR to trigger a preflight request - a request to make sure it’s allowed to actually make the real request. The preflight request is is an OPTIONS request which your server rejects (405, not allowed):

Request URL:http://transport.opendata.ch/v1/locations?x=1y=2 Request Method:OPTIONS

Accept:/ Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Access-Control-Request-Headers:origin, x-requested-with Access-Control-Request-Method:GET Connection:keep-alive Host:transport.opendata.ch Origin:http://tatana.local Referer:http://tatana.local/~marcelstoer/MyApp/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Iron/26.0.1450.0 Chrome/26.0.1450.0 Safari/537.36

I can tell Sencha to stop adding custom headers to the XHR by setting Ext.Ajax.setUseDefaultXhrHeader(false); but it'd be nice if you a) document that CORS is supported b) allow the OPTIONS preflight request

So, besides Access-Control-Allow-Origin: * you'd have to set (at least?) Access-Control-Allow-Headers: x-requested-with and Access-Control-Request-Method: GET,OPTIONS (POST?). Possibly OPTIONS is blocked in general?

Some more info is here: http://remysharp.com/2011/04/21/getting-cors-working/

fabian commented 11 years ago

I see, okay, will have a look at it again, thanks for the detailed report!