Welcome to Abdul Malik Ikhsan's Blog

CORS ( Cross-Origin Resource Sharing ) : connecting multiple site with multiple request method

Posted in Javascript, Teknologi by samsonasik on April 23, 2011

CORS adalah draft teknologi yang dikembangkan oleh W3C sebagai alternatif yang lebih modern ketimbang JSONP. Ketika JSONP hanya men-support  GET request method, CORS juga mensupport POST request method. Teknologi ini dikembangkan karena semakin kompleksnya kebutuhan mashup data di dunia internet. Ide dasar dari CORS ini adalah meng-custom HTTP Header agar client dan server dapat mengetahui satu sama lain apabila request dan response berhasil atau gagal dilakukan.
Kali ini, saya akan mencoba memaparkan tentang contoh implementasi CORS menggunakan jQuery javascript library, dan plugin CORS. Plugin asli dapat didownload di sini , yang akan saya sampaikan di sini sudah saya modifikasi dari aslinya untuk kebutuhan jQuery versi 1.5.
Pertama, kita siapkan dulu jQuery library kita, bisa didownload di sini. Setelah itu, kita buat plugin untuk handle CORS sebagai berikut :

(function($) {
    //activate cors support <-- for jQuery 1.5
    jQuery.support.cors = true;

    $.corsGET = function(url,callback){
        try{
           jQuery.get(url, callback);
        }catch(e){
            // jQuery get() failed, try IE8 CORS, or use the proxy
            if (jQuery.browser.msie && window.XDomainRequest) {
                // Use Microsoft XDR
                var xdr = new XDomainRequest();
                xdr.open("get", url);
                xdr.onload = function() {
                    callback(this.responseText, 'success');
                };
                xdr.send();
            } else{
                try {
                    // Ancient browser, use our proxy
                    var ancientcallback = function() {
                    var textstatus = 'error';
                    var data = 'error';

                    if ((this.readyState == 4)
                        && (this.status == '200')) {
                            textstatus = 'success';
                            data = this.responseText;
                        }
                        callback(data, textstatus);
                    };

                    // proxy_xmlhttp is a separate script you'll have to set up
                    request = new proxy_xmlhttp();
                    request.open('GET', url, true);
                    request.onreadystatechange = ancientcallback;
                    request.send();
                } catch(e) {
                    // Could not fetch using the proxy
                    alert('failed !!! ');
                }
            }
        }
    };

    $.corsPOST = function(url,data,callback){
        try{
            jQuery.post(url, data, callback);
        }catch(e){
             // jQuery post() failed, try IE8 CORS, or use the proxy
            if (jQuery.browser.msie && window.XDomainRequest) {
                // Use XDR
                var xdr = new XDomainRequest();
                xdr.open("post", url);
                xdr.send(params);
                xdr.onload = function() {
                    callback(xdr.responseText, 'success');
                };
            } else{
                try {
                    // Use the proxy to post the data.
                    request = new proxy_xmlhttp();
                    request.open("POST", url, true);
                    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    request.send(params);
                } catch(e2) {
                   // could not post using the proxy
                   alert('failed !!! ');
                }
            }
        }
    };

})(jQuery);

Kita bisa simpan plugin ini dan kita beri nama : jquery.cors.js . Ok, setelah itu kita buat contoh file sebagai requester cross domain kita, contoh sebagai berikut :

<!DOCTYPE html>
<html>
<head>
  <title>
      Test CORS ( Cross-Origin Resource Sharing )
  </title>
  <script type="text/javascript" src="jquery-1.5.2.min.js"></script>
  <script type="text/javascript" src="jquery.cors.js"></script>
  <script type="text/javascript">
     $(document).ready(function(){
         $("#sendDataBtn").click(function(){
            //clear label ...
            $("#resultcors").html();

            if ($("#typeofparameter").val()=='get'){
              $.corsGET('http://service.yourdomain.com?nama='+$("input[name=nama]").val()+'&'+(new Date()).getTime() ,
                function(data){
                  $("#resultcors").html('The response is : '+data);
              });
            }else{
              $.corsPOST('http://service.yourdomain.com?'+(new Date()).getTime() , {  nama: $("input[name=nama]").val() },
                function(data){
                  $("#resultcors").html('The response is : '+data);
              });
            }
         });
     });
  </script>
</head>
<body>
    <input type="text" name="nama" size="50" /> <br />
    type : <select name="typeofparameter" id="typeofparameter">
               <option value="get">GET</option>
               <option value="post">POST</option>
           </select>

    <input type="button" id="sendDataBtn" value="Send Data" />

    <br />
    <label id="resultcors"></label>

</body>
</html>

Kalau sudah, kita buat deh file responder-nya ( kita buat di server lain atau atas nama domain lain).

<?php
// Specify domains from which requests are allowed
header('Access-Control-Allow-Origin: *');
// Specify which request methods are allowed
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
// Additional headers which may be sent along with the CORS request
// The X-Requested-With header allows jQuery requests to go through
header('Access-Control-Allow-Headers: X-Requested-With');
// Set the age to 1 day ( 86400 ) to improve speed/caching.
header('Access-Control-Max-Age: 86400');

// Exit early so the page isn't fully loaded for options requests
if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
    exit();
}

// If raw post data, this could be from IE8 XDomainRequest
// Only use this if you want to populate $_POST in all instances
if (isset($HTTP_RAW_POST_DATA)) {
    $data = explode('&', $HTTP_RAW_POST_DATA);
    foreach ($data as $val) {
       if (!empty($val)) {
         list($key, $value) = explode('=', $val);
         $_POST[$key] = urldecode($value);
       }
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo  '<strong>posted</strong> : '.strtoupper(  $_REQUEST['nama'] );
}

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    echo '<strong>getted </strong> : '.strtoupper(  $_GET['nama'] );
}

Taraaaa….Sehingga jika ditest, akan tampil sebagai berikut :

Gambar :
http://t2.gstatic.com/images?q=tbn:ANd9GcSbW9iPimNholkyrzJ2tvD-uqRQ8_5KkBC4hVLys9XEVh4KTN81

Referensi :
http://plugins.jquery.com/project/cors
http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing
http://en.wikipedia.org/wiki/JSONP
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
http://enable-cors.org/
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
https://developer.mozilla.org/en/http_access_control
http://blueonionsoftware.com/blog.aspx?p=03aff202-4198-4606-b9d6-686fd13697ee
http://msdn.microsoft.com/en-us/library/cc288060%28v=vs.85%29.aspx

5 Responses

Subscribe to comments with RSS.

  1. iwan_susanto said, on June 9, 2011 at 4:43 pm

    Makasih mas atas ilmunya aku minta ya hehehe,,boleh dong minta tutorial javanya j2se

  2. samsonasik said, on June 9, 2011 at 7:20 pm

    sama2, boleh, beberapa modul j2se bisa didownload di sini : https://samsonasik.wordpress.com/download/

  3. yulyanti said, on July 26, 2011 at 7:14 pm

    sediakan file buat di download dong..jadi bisa langsung di download n dicoba dijalankan..umz,,kan lebih efisien..

  4. samsonasik said, on July 27, 2011 at 1:14 am

    kan biar belajar, kalau copy paste namanya ga belajar

  5. Shams said, on December 12, 2013 at 12:36 pm

    ada pustaka lain yang lebih robust?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: