【问题标题】:CORS error in AngularJSAngularJS中的CORS错误
【发布时间】: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.

【问题讨论】:

    标签: javascript angularjs cross-domain cross-platform cors


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 2016-08-15
      • 2017-06-27
      • 2018-04-07
      • 2015-11-01
      • 2016-09-06
      • 2017-11-30
      • 1970-01-01
      • 2017-08-22
      相关资源
      最近更新 更多