2015-04-23 64 views
0

当我使用Fiddler或任何浏览器端的HTTP客户端扩展如Advanced Rest Client时,我可以轻松地从API获取数据。 但是,当我尝试从Angular JS使用相同的API时,CORS问题立即出现。我已经尝试了以下几行来解决AngularJS中的问题,但不幸的是它没有奏效。AngularJS中的CORS错误

appd.config(function ($httpProvider) { 
    // $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
    // $httpProvider.defaults.headers.post['Accept'] = '*/*' 
    $httpProvider.defaults.useXDomain = true; 
    $httpProvider.defaults.withCredentials = true; 
    delete $httpProvider.defaults.headers.common["X-Requested-With"]; 
    $httpProvider.defaults.headers.common["Accept"] = "*/*"; 
    $httpProvider.defaults.headers.common["Content-Type"] = "application/x-www-form-urlencoded"; 
    $httpProvider.defaults.headers.common['Authorization'] = 'Basic encodedpassword='; 
}); 

我得到在Mozilla以下错误:

跨来源请求阻止:

The Same Origin Policy disallows reading the remote resource at http://host/training_webapi. This can be fixed by moving the resource to the same domain or enabling CORS. 

中和铬以下:

XMLHttpRequest cannot load http://host/training_webapi The request was redirected to 'http:host/training_webapi/', which is disallowed for cross-origin requests that require preflight. 

回答

0

您所请求的服务是不允许CORS(不作为响应的一部分发送访问控制)。 您需要将头部Access-Control-Allow-Origin:*作为响应的一部分(它不会)。

看到这个:http://www.html5rocks.com/en/tutorials/cors/

+0

,您好:感谢您的回答。但它适用于Rest-clients。 T.E.提琴手或其他人 – Muffin

0

您可能能够使用$http.jsonp

var url = "http://host/training_webapi?callback=JSON_CALLBACK"; 

$http.jsonp(url) 
    .success(function(data){ 
     console.log(data.found); 
    }); 

工作JSFiddle

另一种选择(因为你没有自己的服务器),可能是代理服务器和URI采用了棱角分明的访问的请求。

还有一点,在代码中的内容标题设置为形式:

$httpProvider.defaults.headers.common["Content-Type"] = "application/x-www-form-urlencoded"; 

你的请求应该被期待

content-type: application/json