简体   繁体   中英

enabling CORS from controller of angular JS

I have a controller with service that would get the json from other server and i came to this

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.

I notice that some of the same issue would be fix by "Access-Control-Allow-Origin": "*" in header my in my case I don't see any progress on fixing it.

this the code for my controller :

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) {


    });

}]);

I added the header but it seem not to fix my cross origin issue. Could anyone drive me by any comments and suggestion on how am i able to get the response from another server source. thank you in advance.

CORS is a server solution - that is - the first request a web client (JS) sends to a different domain (hence cross domain) is an OPTIONS request - which is replied by the origin server with weather or not it respect cross domain requests, if so it answers:

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

Then the browser sends another request - the actual request that was meant to be sent. This whole mechanism takes place automatically. All you have to do is enabling CORS on your server. To enable CORS, here are some useful links:
ASP.NET WEBAPI
APACHE

CORS is something that has to be enabled on the server . If you don't have access to that server you probably won't be able to do what you were hoping. If you do have access you'll need to read up on how to enable it for whatever language the api was written in :)

See here for more info: CORS request is not allowed with AngularJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM