Different ways of doing cross origin requests

Cross origin requests:

Ajax -> CORS -> JSONP -> IFRAMES -> FLASH

Ajax:

– No cross origin by default

CORS:

– modern way

– A regular cross-origin request will turn automatically into a OPTION request. Server answers the OPTION request with either allow or disallow. The server response contains both headers and status code, although headers are way meaningful than status code in this case.

– The OPTION request is an extra round trip to the server, hence can be cached.

– The OPTION request is sent before the regular request is sent. The regular request won’t be sent until the OPTION request has been answered by the server.

JSONP:

– JSON with padding

– Implemented with cross domain script tag.

– The script tag is cross origin by nature.

– For fbapp.com, the basic version is:

<script src="http://facebook.com/all.js"></script>

– Slightly better version:

<script src="http://facebook.com/all.js?varName=result"></script>

– Best version(?):

<script>

var myFunc = function(fbData){

console.log(fbData);

}

document.write('<script src="facebook.com?callback=myFunc"></script>');

//facebook.com returns

//'myFunc( {"username":"shao", "gender":"male"} )'

//it is a JSON padded with a function call

//hence JSONP

</script>

– Always GET

– Note: document.write() is async; MIME is application/json(?)

IFRAMES:

– Old technique and still in use. Especially in China where IE6 still has 20% market share.

– Might be the only way to do cross-origin POST request in the client side.

– Check http://stocktwits.com/. Heard they did tons of those.

FLASH:

– Dinosaur. Steve Jobs was right.

Native ways to solve cross origin requests:

– Option 1: encrypt the cookie such that only requests originated from the same domain is valid.

– Option 2: white list / black list maintained by each website allowing cross-origin ajax request.

Advertisements
Standard

One thought on “Different ways of doing cross origin requests

  1. Pingback: Day 22, Node.js | Shao

Comments are closed.