简体   繁体   中英

How to enable CORS in angular js

I am having a controller.js

ListNewsCtrl.$inject = ['$http', '$scope', 'datacontext'];
function ListNewsCtrl( $http, $scope, datacontext) {
    $scope.names = [];
    $http.get("http://www.w3schools.com/website/Customers_JSON.php")
                .success(function (response) {$scope.names = response;console.log($scope.names)});
};

I get the data that I want. But when I change to a different site I get the followinf msg :

XMLHttpRequest cannot load https://URL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3424' is therefore not allowed access. The response had HTTP status code 404.

The information I am trying to access are not requiring access token ?

The solution to my answer would be this :

http://blog.novanet.no/angularjs-with-jsonp-and-how-i-get-to-work-on-time/#2

However,I get this error : Uncaught SyntaxError: Unexpected token : I get small syntax issues . But at least I can see my data

CORS is enabled server-side. The domain you're requesting does not allow CORS requests, and that is not something you can edit or configure on the client end.

If the domain does allow CORS, then whatever you're using to host your local web server on localhost is not allowing it.

If cross-site requests are allowed, try

$http.jsonp("http://www.w3schools.com/website/Customers_JSON.php")
    .success(function(data){
        console.log(data);
});

I would not say its a perfect approach but better workaround for cors.

The Yahoo! Query Language is an expressive SQL-like language that lets you query, filter, and join data across Web services. Great thing about Yahoo YQL is that it is CORS-enabled :)

Client -> YQL -> API Server

Run Sample Here

 $.getJSON("http://query.yahooapis.com/v1/public/yql", { q: "select * from json where url=\\"https://erikberg.com/mlb/standings.json\\"", format: "json" }, function (data) { if (data.query.results) { alert(data.query.results.json.standing); } else { alert('no such code: ' + code); } } ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Here is a cool Tutorial

This will at least solve your cors problem in different ways.

Happy Helping!

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