tom
tom

Reputation: 729

$http Cross Origin Request Blocked by Angular JS

I am trying to implement search suggestion using one of our Suggestions API "https://SuggestionsAPI.net/suggest?key=xyz" which is working fine with Ajax GET request but when I am trying to use it with Angular $http service, it is throwing me error is console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote 
resource at https://SuggestionsAPI.net/suggest?key=xyz. This can be fixed by moving the 
resource to the same domain or enabling CORS.

Further I tried :

$httpProvider.defaults.headers.get = { 'Access-Control-Allow-Origin': '*' };
$httpProvider.defaults.headers.get = { 'Access-Control-Request-Headers': 'X-Requested-With, accept, content-type' };
$httpProvider.defaults.headers.get = { 'Access-Control-Allow-Methods': 'GET, POST' };
$httpProvider.defaults.headers.get = { 'dataType': 'jsonp' };

I am stuck here thinking why same GET request is blocked by browser when using Angular JS. Please suggest me to eliminate it.

EDIT: My next step id to assign the suggestions inside a function:

app.directive('autoComplete', ['AutoCompleteService', function (AutoCompleteService) {
return {
    restrict: 'A',
    link: function (scope, elem, attr, ctrl) {
        elem.autocomplete({
            source: function (searchTerm, response) {
                AutoCompleteService.search(searchTerm.term).then(function (autocompleteResults) {
                    response($.map(autocompleteResults, function (autocompleteResult) {
                        return {
                            label: autocompleteResult.JumboID,
                            value: autocompleteResult.JumboID
                        }
                    }))
                });
            },
            minLength: 3,
            select: function (event, selectedItem) {
                // Do something with the selected item, e.g. 
                scope.yourObject = selectedItem.item.value;
                scope.$apply();
                event.preventDefault();
            }
        });
    }
};

}]);

Upvotes: 2

Views: 7347

Answers (1)

A.B
A.B

Reputation: 20445

append callback=JSON_CALLBACK to your url like https://SuggestionsAPI.net/suggest?key=xyz&callback=JSON_CALLBACK

then use jsonp

$http.jsonp(url).
    success(function(data, status, headers, config) {
        //here
    }).
    error(function(data, status, headers, config) {
      //
    });

Upvotes: 2

Related Questions