Javascript AngularJS CORS问题

Javascript AngularJS CORS问题,javascript,angularjs,cors,asp.net-web-api,Javascript,Angularjs,Cors,Asp.net Web Api,我已经搜索了200多个站点(可能有些夸张,但没有太多),了解如何使用angularjs处理cors。我们有一台运行web API服务器的本地计算机。我们正在开发一个客户端,该客户端调用API获取数据。从服务器运行客户机时,我们接收数据没有问题。当我们从另一个域运行它时,当我们试图获取数据时,会得到一个红色200响应和一个空白响应。下面是一些代码: var myApp = angular.module('Project', ['ngResource']); myApp.config(functi

我已经搜索了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,但得到了相同的响应(或没有):

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

完成这项任务已经三天了


非常感谢您的帮助。提前感谢。

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

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

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


有关更多详细信息,请参阅本文:

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

该包名为
Microsoft.OWin.Cors

WebiApiConfig.cs
中输入如下内容:

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

如果你想把数据发布到你的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();
            }

        } 

    }
}

您需要稍微修改一下Web API以处理跨域请求。 在Web Api项目中包括Microsoft Asp Net Server Cors库,再进行一些代码级修改,就可以开始了。更多信息,请看一看


您的角度部分完全正常。

所以您的GET请求失败了?请显示请求和响应的标题。如果您只需打开Chrome上的网络选项卡并将所有内容都包含在headers部分,那么这将是最简单的。如果您使用Wildfly(JBOSS 8.X)查看Chrome中devtools中的XhreQuest for Instance,您是否可以看到跨域标题和选项握手,我编写了一个名为CorsFilter的简单Java类,它将一些CORS头添加到对web服务的响应中。该示例的链接位于底部。指向您个人博客的链接似乎已断开。
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();
            }

        } 

    }
}