Cross Origin Resource Sharing or using ajax sensibly

By default ajax requests that go across domains are blocked by most modern browsers, read Chrome, Firefox and Internet Explorer 8+.

To enable this functionality you need to add new headers to your sever specify the domains that can access your data or just let anyone in.

Full details can be found here: http://enable-cors.org/index.html

If you cannot be bothered to read the article then you just need to add the following headers.

  1. Access-Control-Allow-Headers – Try X-Requested-With, Content-Type, Accept
  2. Access-Control-Allow-MethodsGET, POST, PUT, DELETE, OPTIONS
  3. Access-Control-Allow-Origin*
  4. AllowGET, POST, PUT, HEAD, DELETE, TRACE, COPY, LOCK, MKCOL, MOVE, PROPFIND, PROPPATCH, UNLOCK, REPORT, MKACTIVITY, CHECKOUT, MERGE, M-SEARCH, NOTIFY, SUBSCRIBE, UNSUBSCRIBE, PATCH, SEARCH

Obviously the above is over kill and can be cut down to meet your specific requirements.
For example (2) could be reduced but you may find you have to keep the OPTIONS value in as this can be issued by the browser before a GET or POST to determine what the server supports (a preflight request).
The value of “*” for (3) allows any site to access your data using XmlHttpRequest, this could be reduced to a list of space separated domains if required.
The final list (4) is again over the top and could be reduced significantly.

If you happen to be using OAuth 2.0 then and sending the access_token via the header, rather than the querystring, then you need to add Authorize to the Access-Control-Allow-Headers, as the token should be sent using the Bearer field.
In fact if you use any custom headers then you’ll need to add them all as CORS strips them all out.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.