Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top