【问题标题】:AngularJS CORS IssuesAngularJS CORS 问题
【发布时间】:2013-07-19 08:33:33
【问题描述】:

我已经搜索了 200 多个网站(可能有些夸张,但不是很多)关于如何使用 angularjs 处理 cors。我们有一台运行 Web API 服务器的本地机器。我们正在开发一个调用 API 获取数据的客户端。从服务器运行客户端时,我们接收数据没有问题。当我们从不同的域运行它时,我们会在尝试获取数据时收到红色的 200 响应和空白响应。这是一些代码:

var myApp = angular.module('Project', ['ngResource']);

myApp.config(function($routeProvider){
    $routeProvider.
        when('/new', {templateUrl:'templates/new.html', controller:'EditProjectController'}).
        when('/mobile', {templateUrl:'templates/mobile.html', controller:'ProjectController'}).
        when('/it', {templateUrl:'templates/it.html', controller:'ProjectController'}).
        when('/writing', {templateUrl:'templates/writing.html', controller:'ProjectController'}).
        when('/all', { templateUrl: 'templates/all.html' }).
        when('/login', { templateUrl: 'partials/_login.html' }).
        otherwise({ redirectTo: '/all' });
});
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);



myApp.controller('ProjectController', 
function myApp($scope, $http, projectDataService, userLoginService) {
    $http.defaults.useXDomain = true;
    $scope.loadProject = function(){
        projectDataService.getProject(function(project){
            $scope.project = project;
            })


    };
    $scope.loadProject();
}

);

myApp.factory('projectDataService', function ($resource, $q) {
var resource = $resource('http://webapiserver/api/:id', { id: '@id' });
return {
    getProject: function () {
        var deferred = $q.defer();
        resource.query({ id: 'project' },
            function (project) {
                deferred.resolve(project);
            },
            function (response) {
                deferred.reject(response);
            });

        return deferred.promise;
    },
    save: function (project) {
        var deferred = $q.defer();
        project.id = 'project/9';
        resource.save(project,
            function (response) { deferred.resolve(response); },
            function (response) { deferred.reject(response); }
            );
        return deferred.promise;
    }
};
});

我也尝试过使用 $http 但我得到了相同的响应(或没有响应):

myApp.factory("projectDataService", function ($http) {

return {
    getProject: function (successcb) {
        $http.get("http://webapiserver/api/project").
        success(function (data, status, headers, config) {
            successcb(data);
        }).
        error(function (data, status, headers, config) {

    }
};
});

当我只是浏览到在浏览器中提供 json 的 url 时,它会吐出数据。在服务器上,我们允许跨域来源,这在我之前的声明中很明显。如您所见,我正在 myApp.config 中实现标头覆盖,我什至尝试将其直接放在我的控制器中...没有区别...

这个任务现在有 3 天了。

对此的帮助不胜感激。提前致谢。

【问题讨论】:

  • 所以你的 GET 请求失败了?请显示请求和响应的标头。如果您只需在 Chrome 上打开网络选项卡并将所有内容包含在标题部分中,这将是最简单的。
  • 例如,如果您在 Chrome 的 devtools 中查看 XHRRequest,您能看到跨域标头和选项握手吗

标签: javascript angularjs cors asp.net-web-api


【解决方案1】:

您可能需要稍微更改您的 Web API。我遇到了同样的问题并写了一篇关于如何解决这个问题的帖子。

我使用 Sinatra 作为 API,我不知道您的网络服务使用什么语言,但我想您可以应用它。基本上,您需要通过定义允许哪些来源和哪些 HTTP 方法来配置您的服务器以接受 CORS 调用。

你说你已经在你的服务器上启用了它,但你到底做了什么?

查看这篇文章了解更多详情:CORS with angular.js

【讨论】:

  • 如果您使用的是 Wildfly (JBOSS 8.X),我编写了一个名为 CorsFilter 的简单 Java 类,它将一些 CORS 标头添加到对 Web 服务的响应中。该示例的链接位于底部的stackoverflow.com/questions/23346863/…
  • 您个人博客的链接似乎已损坏。
【解决方案2】:

如果是ASP.NETWebAPI,需要在web服务器启动时安装CORS包并初始化CORS

包名为Microsoft.OWin.Cors

WebiApiConfig.cs 中输入如下内容:

var cors = new EnabledCorsAttribute("*", "*", "DataServiceVersion, MaxDataServiceVersion");
config.EnableCors(cors);

【讨论】:

    【解决方案3】:

    您需要稍微修改您的 Web API 以处理跨域请求。 在 Web Api 项目中包含 Microsoft Asp-Net Server Cors 库和一些代码级别的修改,您就可以开始了。更多请看here.

    你的 Angular 部分完全没问题。

    【讨论】:

      【解决方案4】:

      如果您想要将数据发布到您的 WebApi,那么您需要做更多的工作才能让 Chrome 正常工作。您需要拦截预检并将客户端来源作为允许的来源。

      如果有更好的解决方案,那么在专门解决这个问题很多天后,我找不到它。最后,这对我有用。

      祝你好运……

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Http;
      using System.Web.Routing;
      
      namespace MashupCoreApiApi
      {
          public class WebApiApplication : System.Web.HttpApplication
          {
              protected void Application_Start()
              {
                  GlobalConfiguration.Configure(WebApiConfig.Register);
              }
      
      
              protected void Application_BeginRequest(object sender, EventArgs e)
              {
      
                  if (Context.Request.Path.Contains("api/") && Context.Request.HttpMethod == "OPTIONS")
                  {
      
                      Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
                      Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                      Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST PUT, DELETE, OPTIONS");
                      Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                      Context.Response.End();
                  }
      
              } 
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 2017-02-13
        • 2015-02-23
        • 2017-05-07
        • 2013-09-06
        • 2013-11-20
        • 2019-05-17
        • 2019-02-04
        • 2014-05-04
        相关资源
        最近更新 更多