AngularJS CORS don't send all cookies with credential, but jQuery send
Asked Answered
S

1

5

I'm using AngularJS v1.2.16 in my frontend. I've created a simple service:

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;
  }];
});

When i try to get list of sites in my controller:

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

Angular doesn't send cookies with request, and I can't get list of sites.

But when I send same request by jQuery:

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

Cookies sent with request and I can get list of sites.

Tell me, please, where is my mistake?

Shellacking answered 6/5, 2014 at 6:35 Comment(0)
K
11

Since the $resource service is a factory of $http have you try to set the withCredentials default value to true of your $httpProvider in your app config ?

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

Referring to the Angular docs, your syntax seems correct for the withCredentials.

Knuckleduster answered 26/5, 2014 at 14:25 Comment(1)
This answer solved it for me! I couldn't get it to work unless it was a default.Trusting

© 2022 - 2024 — McMap. All rights reserved.