Skip to content

CORS And JSONP

Andrew Yates edited this page Sep 15, 2015 · 2 revisions

Introduction

CORS and JSON-P represent ways of accessing data from an external resource whilst avoiding the same-origin policy restrictions in web browsers.

CORS

Cross origin resource sharing (CORS) is a way for web browsers to request resources from a domain other than the one JavaScript/HTML was originally loaded from. CORS works by the client sending a HTTP header called Origin and providing the originating domain name e.g. Origin: http://www.example.com. The responding server will return an Access-Control-Allow-Origin header back either with the domain of the origin or a *. This means the given domain is allowed to use the origin and not violate same origin policy or any domain can use the data and not violate the same origin policy.

Ensembl REST will return a Access-Control-Allow-Origin: * response header when any Origin request header is sent. You should consider CORS as the best way to access data in Ensembl REST from a browser.

JSON-P

JSON Padded (JSON-P) represents an older way of performing pan-domain requests without violating same-origin policy. It is limited to only supporting GET requests and works by a hack in browsers to allow to loading of JavaScript script files from any resource. The system works like so:

  • Make a GET request and pass through a parameter called callback e.g. ?callback=myrandomfunctionname
  • The remote server performs the request and generates a JSON document e.g. {"name":"wibble"}
  • The remote server then pads the JSON document with a function call e.g. myrandomfunctionname({"name":"wibble"})
  • The client receives this padded JSON which is evaluated within a <script> tag and the JavaScript developer calls the function myrandomfunctionname which returns the JSON document
  • Requests are made with the MIME type text/javascript

Whilst this methodology works well in older browsers it is not recommended because of their openness to cross-site request forgery attacks.