【问题标题】:AngularJS CORS don't send all cookies with credential, but jQuery sendAngularJS CORS 不会发送所有带有凭据的 cookie,但 jQuery 会发送
【发布时间】:2014-06-22 15:24:13
【问题描述】:

我在前端使用 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;
  }];
});

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

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,我可以获取网站列表。

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

【问题讨论】:

    标签: jquery angularjs http cors angular-resource


    【解决方案1】:

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

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

    参考 Angular docswithCredentials 的语法似乎是正确的。

    【讨论】:

    • 这个答案为我解决了!除非它是默认设置,否则我无法让它工作。
    猜你喜欢
    • 2015-02-11
    • 2013-12-24
    • 2012-04-07
    • 2021-10-13
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2018-01-08
    相关资源
    最近更新 更多