簡體   English   中英

從角度JS控制器啟用CORS

[英]enabling CORS from controller of angular JS

我有一個帶有服務的控制器,該服務將從其他服務器獲取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.

我注意到某些相同的問題將通過標題中的"Access-Control-Allow-Origin": "*"進行修復"Access-Control-Allow-Origin": "*"在我的頭文件中, "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) {


    });

}]);

我添加了標題,但似乎無法解決我的跨源問題。 任何人都可以通過關於如何從另一個服務器源獲得響應的任何評論和建議來驅使我。 先感謝您。

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
亞太地區

CORS是必須在服務器上啟用的功能。 如果您無權訪問該服務器,則可能無法執行您希望的操作。 如果您具有訪問權限,則需要閱讀有關如何使用api編寫的任何語言啟用它的信息:)

查看更多信息: AngularJS不允許CORS請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM