AngularJS CORS不会发送带有凭据的所有cookie,但jQuery会发送

J S*_*rel 5 jquery http cors angularjs angular-resource

我在我的前端使用AngularJS v1.2.16.我创建了一个简单的服务:

app.provider('Site', function () {

  var apiServer = 'http://api.example.com';

  this.$get = ['$resource', function ($resource) {
    var site = $resource(apiServer + '/sites/:action:id', {}, {
      query: {
        withCredentials: true
      },
      checkDomain: {
        method: 'POST',
        withCredentials: true,
        params: {
          action: 'checkDomain'
        }
      },
      save: {
        method: 'PUT',
        withCredentials: true
      }
    });

    return site;
  }];
});
Run Code Online (Sandbox Code Playgroud)

当我尝试获取控制器中的网站列表时:

app.controller('SitesCtrl', ['$scope', 'Site', function ($scope, Site) {
   $scope.sites = Site.query();
}]);
Run Code Online (Sandbox Code Playgroud)

Angular不会发送带有请求的cookie,我无法获取网站列表.

但是当我通过jQuery发送相同的请求时:

$.ajax({
  type: 'GET',
  url: 'http://api.example.com/sites',
  xhrFields: {
    withCredentials: true
  },
  success: function (data) {
    console.log(data);
  }
});
Run Code Online (Sandbox Code Playgroud)

随请求发送的Cookie,我可以获取网站列表.

请告诉我,我的错误在哪里?

Bal*_*zar 9

由于该$resource服务是您的工厂,$http您是否尝试在应用配置中将withCredentials默认值设置为true $httpProvider?

.config(function ($httpProvider) {
  $httpProvider.defaults.withCredentials = true;
}
Run Code Online (Sandbox Code Playgroud)

参考Angular 文档,您的语法似乎是正确的withCredentials.