我在前端使用 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;
}];
});
当我尝试在我的 Controller 中获取站点列表时:
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,我可以获得站点列表。
请告诉我,我的错误在哪里?
最佳答案
由于 $resource
服务是 $http
的工厂,您是否尝试将 withCredentials
默认值设置为 true 您的 $httpProvider
在您的应用程序配置中?
.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
引用 Angular docs ,对于 withCredentials
,您的语法似乎是正确的。
关于jquery - AngularJS CORS 不会发送所有带有凭据的 cookie,但 jQuery 会发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23487499/