One of the great things about API’s that return JSON is that you can use them directly from the browser. This means you can serve an entirely static page, and still show interesting dynamic data. But for security reasons browsers only allows you to send Ajax requests to the domain you loaded the page from. This serverely restricts the possibilites of using third party API’s directly from the browser.
Fortunately there exists ways to circumvent this restriction. The most popular is JSONP (JSON with padding). I won’t go into JSONP in this post, but suffice it to say that because the method is based on inserting a script tag in the page, it only works for GET requests.
Enter CORS (Cross-Origin Resource Sharing)…
CORS is a method for the server to tell the browser that it is safe to do cross origin requests to this endpoint. It works by simply adding the header Access-Control-Allow-Origin to the response. Set it to * (wildcard) to allow all domains. At resmio we have CORS enabled for our API. You can see it in action by doing
curl -I -k https://resmio.com/api/v1
This allows us to quickly throw up a new site with no server side code, that consumes our public API. Incidentally we’ve built a JavaScript library that makes it easy to access our API, that we can reuse on all sites.
When is it safe to use CORS?
You should only allow CORS for stuff that does not use session cookies, otherwise you’d be susceptible to Cross-site request forgery attacks.
Browser support?
CORS is supported by all modern browsers. One caveat is that in Internet Explorer, CORS is not supported by the regular Ajax request object. Instead you have to use an XDomainRequest object. If you use jQuery you can include the ajaxTransport xdr.js for IE support.
Thus, if you already have an API you can make it easy to use for everybody by just adding one header to your responses.

Ingen kommentarer:
Send en kommentar