$ http Cross Origin请求被Angular JS阻止

时间:2014-12-30 05:27:35

标签: javascript angularjs cors

我正在尝试使用我们的建议API" https://SuggestionsAPI.net/suggest?key=xyz"来实施搜索建议。这与Ajax GET请求工作正常,但当我尝试使用它与Angular $ http服务时,它抛出我的错误是控制台:

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.

我进一步尝试了:

$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' };

我在这里想到为什么在使用Angular JS时浏览器会阻止相同的GET请求。请建议我消除它。

编辑:我的下一步是在函数内分配建议:

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();
            }
        });
    }
};

}]);

1 个答案:

答案 0 :(得分:2)

callback=JSON_CALLBACK附加到您的网址https://SuggestionsAPI.net/suggest?key=xyz&callback=JSON_CALLBACK

然后使用jsonp

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