Go4Expert

Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/articles/javascript-tutorials/)
-   -   Share Cross-Domain Data using CORS in JavaScript (http://www.go4expert.com/articles/share-cross-domain-data-using-cors-t29523/)

pradeep 2Mar2013 13:51

Share Cross-Domain Data using CORS in JavaScript
 
AJAX was a boon to web development and web applications like GMail etc. millions of site have since implemented AJAX based features on their websites, the idea of asynchronously accessing content was wonderful but AJAX was limited only to the same domain (same origin) as the page requesting the content. Cross-Origin Resource Sharing brought an end to this limitation where the remote server can allow/deny any domain on it's discretion.

Now using 3rd party resources via AJAX is easier & secure. Almost all the current web browsers (Firefox, IE, Chrome, Safari, Opera, etc.) support CORS so there's not much need to worry about compatibility, for an exhaustive TOC of browser compatibility visit http://caniuse.com/#feat=cors. In this article we'll look at how CORS works & and how to implement it.

How CORS Works



CORS adds new HTTP headers to request/server resources to allowed domains. It's the browser's responsibility to check and enforce restrictions, the browser when it encounters the first cross-origin request, checks with the target domains using the HTTP OPTIONS method for permissions to access the resource, in response servers will tell the allowed domains, and may also specify additional data (like cookies, basic auth) required for the requests.

Implementing CORS



As I said earlier the CORS request is just like the normal AJAX request, follow the examples below, in my examples I have used jQuery instead of native JS for ease.

This is how the client side JavaScript should look like, I'll run this JS on a1.go4expert.com, and request resource from a2.go4expert.com.

HTML Code:

<html>
 <head>
  <title>Test CORS</title>
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 </head>

 <body>
    <script type="text/javascript">
    $(document).ready(function () {
        var url = 'http://a2.go4expert.com/cors.pl';
        $.ajax({
            url: url,
            type: "GET",
            data: {
                name: "Anjali"
            },
            success: function (data, textStatus, jqXHR) {
                alert(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("failure");
            }
        });
    });
    </script>
 </body>
</html>

And, now on the server side, we'll need to code our script to allow CORS, see the example Perl script I created below:

Code: Perl

use strict;
use warnings;
use CGI;

my $cgi = new CGI;

## we will all required headers in the hash
my %headers;

if ( $ENV{REQUEST_METHOD} eq 'OPTIONS' ) {

    ## specify allowed origin
    $headers{'-access_control_allow_origin'}      = 'http://a1.go4expert.com';
    $headers{'-access_control_allow_credentials'} = 'true';
    ## specify allowed HTTP methods
    $headers{'-access_control_allow_methods'} = 'GET, POST, OPTIONS';
    ## how long before reauthorizing again, in seconds
    $headers{'-access_control_max_age'}       = '604800';
    $headers{'-access_control_allow_headers'} = 'x-requested-with';

    print $cgi->header(%headers), "Go Ahead";
}
else {
    print $cgi->header, "CORS looks good ".$cgi->param('name')."!!";
}


That's all that need to get CORS working, rest all is regular AJAX, get started and keep us posted in case you have any problems.


All times are GMT +5.5. The time now is 12:03.