javascript 登录后,Angular $http 在每个请求上设置 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30492239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular $http set cookie on each request after login
提问by marlonlaan
I'm having troubles with $http calls in AngularJS. I've created the following services
我在 AngularJS 中调用 $http 时遇到问题。我创建了以下服务
crApp.service('authService', function ($http) {
var urlBase = 'http://192.168.xx.xx:8081';
// POST api/login/
this.login = function (credentials) {
return $http.post(urlBase + "/api/login", credentials);
};
// POST api/logout/
this.logout = function () {
return $http.post(urlBase + "/api/logout/", "");
};
}); //end service
crApp.service('dataService', function ($http) {
var urlBase = 'http://192.168.xx.xx:8081';
// POST api/query/
this.pull = function (query) {
return $http.post(urlBase + "/api/query", query);
};
From the controller I call the login method:
我从控制器调用 login 方法:
$scope.login = function(){
authService.login(credentials)
.success(function(data) {
console.log("RESULT LOGIN: " + data );
})
.error(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
};
So far so good and I receive a response where a cookie is set:
到目前为止一切顺利,我收到了一个设置了 cookie 的回复:
After succesfull login I call the following method:
成功登录后,我调用以下方法:
var locations = { query: "from location select uid, name, description, address, phone", dataFormat: "verbose" };
$scope.getLocations = function() {
dataService.pull(portals)
.success(function (data) {
console.log("RESULT QUERY: " + data)
})
.error(function(data, status, headers, config) {
console.log("Query niet gelukt!");
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
};
Result:
结果:
So cookie is not set in the headers. I'm using AngularJS 1.3.15 and calls are made to a remote server on a different domain, but it does work in the REST Client tool in WebStorm (Jetbrains). So it must be something i'm missing in Angular!??
所以 cookie 没有设置在标头中。我使用的是 AngularJS 1.3.15 并且调用了不同域上的远程服务器,但它确实可以在 WebStorm (Jetbrains) 的 REST 客户端工具中工作。所以它一定是我在 Angular 中缺少的东西!??
Hopefully someone can help me out.
希望有人可以帮助我。
回答by Scott
You need to set withCredentials = true
in the $http
config to allow cookies to be set on CORS requests. This article explains more about cookies and CORS.
您需要withCredentials = true
在$http
配置中设置以允许在 CORS 请求上设置 cookie。本文解释了有关 cookie 和 CORS 的更多信息。
In your app config:
在您的应用配置中:
$httpProvider.defaults.withCredentials = true;
For example:
例如:
angular.module('myApp', [])
.config(['$httpProvider'){
$httpProvider.defaults.withCredentials = true;
}]);
You can read about this option in the $http
provider documentation.
您可以在$http
提供者文档中阅读有关此选项的信息。