Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 506
J Sorel Avatar asked May 06 '14 06:05

J Sorel


1 Answers

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.

like image 91
Preview Avatar answered Nov 06 '22 19:11

Preview