Sunday, August 17, 2014

CORS - Cross Origin Resources Sharing - Isu

JSON FTW... yeay.... everything is JSON... membuatkan hidup anda gembira... hahahhahahhaa.... tapi hilang kegembiraan itu bila error x leh guna JSON yg dah di kongsikan.... hahahahhaha....

Isu yang selalu timbul... xmlhttprequest gagal sebab cross domain request oleh javascript anda... tension kan?... hahhaha

Solusi yg saya pakai adalah... create satu simple server side scipt (perl/php) untuk jalankan tugas ini utk anda. dlm kes ni saya tunjukkan cth mudah mengunakan PHP.

PHP:


$qry_str = $_POST["json"];
if(!$qry_str){
    $qry_str = $_GET["json"];
}

$ch = curl_init();

header("Content-type: application/json");

$http_origin = $_SERVER['HTTP_ORIGIN'];
if(!$http_origin){$http_origin = $_SERVER['HTTP_REFERER'];}

//replace 1234|abcd|... with ur regex origin domain 
if (preg_match('/(1234|abcd)/i', $http_origin)){  
    header("Access-Control-Allow-Origin: $http_origin");n
}

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '10');
$content = trim(curl_exec($ch));

curl_close($ch);

if($content){
    if ($GET['callback'] != ''){
        print $GET['callback']."( $content )";
    }else{
        $json = json_decode($content);
        
        if(json_last_error() == JSON_ERROR_NONE){
            print $content;
        }else{
            print '{"status": "ERROR","errormsg" : "Invalid Content"}';
        }
        exit; 
    }
    exit;
    
}else{
    print '{"status": "ERROR", "errormsg" : "Empty '.$_GET["json"].'"}';
    exit;
}


kita namakan nya 'json.php'

di javascript kita pula, saya bg cth mengunakan angularjs $http method.

var jsonurl = "http://abc.com/capaian/ke/file/json.json";
        
$http({
    method: 'GET', 
    url: '/json.php?json=' + jsonurl 
}).
success(function(data, status, headers, config) {
    //cek if status == ERROR utk kenalpasti jika ada masalah dgn data anda.
    $scope.prosesdataanda(data)
   
}).
error(function(data, status, headers, config) {
    //hati-hati disini... error bila ada masalah di 'json.php' bukan sumber json anda.
    console.log(data, status);
});

Setel

No comments: