2014-10-30 11 views
0

的控制器實現CORS我有一個服務控制器,將來自其它服務器獲取JSON和我來到這個

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the resource to the same domain or enabling CORS.從角JS

我注意到一些相同的問題,將通過"Access-Control-Allow-Origin": "*"是修復在我的情況我在我的情況下,我沒有看到任何進展修復它。

這對我的控制器代碼:

var myApp = angular.module('cplanner',[]); 

myApp.controller('GetItemCtrl', ['$scope', '$http', function($scope, $http) { 

    var itemUrl = 'http:somesite.com'; 

    //console.log(itemUrl); 
    $http({url: itemUrl, 
    dataType: 'json', 
    method: 'POST', 
    dataType : 'json', 
    headers: { 
     "Access-Control-Allow-Origin": "*", 
     "Access-Control-Allow-Methods": "POST, GET, OPTIONS, PATCH, DELETE", 
     "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept" 
    }, 
    xhrFields: { 
     withCredentials: true 
    }}).success(function(data, status, headers, config) { 
     //check if the response has ok status 
     if(data.status == "ok"){ 
     console.log(data.data); 
      $scope.items = data.data; 
     } 


     }).error(function(data, status, headers, config) { 


    }); 

}]); 

我加入了頭,但它似乎並沒有解決我的交叉起源問題。任何人都可以通過關於如何從其他服務器源獲得響應的任何意見和建議來驅動我。 預先感謝您。

回答

0

CORS是必須啓用服務器。如果您無法訪問該服務器,則可能無法執行您所期望的操作。如果你有機會,你將需要在如何激活它讀了任何一種語言的API寫於:)

這裏看到更多的信息:CORS request is not allowed with AngularJS

+0

我看,但我沒有訪問我的服務器,是有可能在htaccess的這樣做呢? – CaffeineShots 2014-10-30 06:05:35

+0

請參閱http://enable-cors.org/server_apache.html – Tomer 2014-10-30 06:06:42

+0

@caffeineshots您可以使用JSONP或其他東西嗎?你的意思是你的web服務器或API服務器上的htaccess? – John 2014-10-30 06:10:14

2

CORS是服務器解決方案 - 這是 - 一個Web客戶端(JS)發送到不同域(因此跨域)的第一個請求是一個OPTIONS請求 - 由源服務器通過天氣回覆或不尊重跨域請求,如果是這樣的話,它會回答:

"Access-Control-Allow-Origin": "*", 
    "Access-Control-Allow-Methods": "POST, GET, OPTIONS, PATCH, DELETE", 
    "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept" 

然後瀏覽器發送另一個請求 - 實際的要發送的請求。 這整個機制自動發生。你所要做的就是在服務器上啓用CORS。 要啓用CORS,這裏有一些有用的鏈接:
ASP.NET WEBAPI
APACHE