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

标签 jquery angularjs http cors 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;
  }];
});

当我尝试在我的 Controller 中获取站点列表时:

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

Angular 不随请求发送 cookie,我无法获取站点列表。

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

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

随请求发送 Cookie,我可以获得站点列表。

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

最佳答案

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

.config(function ($httpProvider) {
  $httpProvider.defaults.withCredentials = true;
}

引用 Angular docs ,对于 withCredentials,您的语法似乎是正确的。

关于jquery - AngularJS CORS 不会发送所有带有凭据的 cookie,但 jQuery 会发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23487499/

相关文章:

javascript - DOM 不更新

angularjs - 设备在线时如何将离线数据库与 Firebase 同步?

javascript - 如何以最小化安全的方式声明 Angular Bootstrap 模式

http - 如何传递 'XML' 输入以使用 Http 适配器在 IBM Mobile First 中使用 API

http - URL中的 '@'是什么意思?

javascript - 使用 Web API 时,jQuery $.ajax() 方法未正确设置 contentType

Javascript:将键盘输入添加到计算器

javascript - 如何获取 Facebook 好友的生日?

javascript - 如何在 jQuery Mobile 中检测/查询当前正在进行的变更页面/转换?

javascript - 无法从 Protractor 测试中的元素值返回字符串