2014-05-06 26 views
5

我在前端使用AngularJS v1.2.16。我創建了一個簡單的服務:AngularJS CORS不發送所有帶有憑證的cookie,但jQuery發送

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

角不請求發送cookie,而我不能讓列表的網站。

但是,當我的jQuery發送相同的請求:與請求一起發送

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

餅乾,我可以得到網站的列表。

請告訴我,我的錯誤在哪裏?

回答

8

由於$resource服務是$http工廠已經嘗試設置withCredentials默認值您$httpProvider真正在你的應用程序配置?

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

參考的角度docs,你的語法似乎爲withCredentials正確。

+0

這個答案爲我解決了!除非是默認設置,否則我無法使其工作。 – Tillman32