AngularJS中的CORS错误

Posted

技术标签:

【中文标题】AngularJS中的CORS错误【英文标题】:CORS error in AngularJS 【发布时间】:2015-07-01 10:10:18 【问题描述】:

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

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.

并在 Chrome 中关注:

 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.

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

您好,感谢您的回答。但它适用于 Rest-clients。 T.E.提琴手或其他人【参考方案2】:

您也许可以使用$http.jsonp。

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

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

工作JSFiddle

另一种选择(因为您不拥有服务器),可能是在您的服务器上代理请求并使用 Angular 访问该 URI。

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

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

您的请求应该是预期的

content-type: application/json

【讨论】:

以上是关于AngularJS中的CORS错误的主要内容,如果未能解决你的问题,请参考以下文章

angularjs + PHP应用程序中的CORS错误

如何处理 Spring Boot、AngularJS 应用程序中的 CORS 错误?

chrome 中的 Angularjs 应用程序中的 CORS 错误访问 .NET Web Api

在 Angularjs 中的 IE10+ 中访问被拒绝 CORs 请求,需要跨源资源共享错误(信息?)

angularJS发布CORS

AngularJS的CORS错误,解决方法有啥?