带凭据的 AngularJS [英] AngularJS withCredentials
问题描述
我一直在研究一个 AngularJS 项目,该项目必须将 AJAX 调用发送到一个 restfull 网络服务.这个网络服务在另一个域上,所以我必须在服务器上启用 cors.我通过设置这些标题来做到这一点:
I've been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server. I did this by setting these headers:
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
我可以将 AJAX 请求从 AngularJS 发送到后端,但是当我尝试获取会话的属性时遇到了问题.我相信这是因为 sessionid cookie 没有发送到后端.
I'm able to send AJAX requests from AngularJS to the backend but I'm facing a problem when I try to get an attribute of a session. I believe this is because the sessionid cookie doesn't get send to the backend.
通过将 withCredentials 设置为 true,我能够在 jQuery 中解决此问题.
I was able to fix this in jQuery by setting withCredentials to true.
$("#login").click(function() {
$.ajax({
url: "http://localhost:8080/api/login",
data : '{"identifier" : "admin", "password" : "admin"}',
contentType : 'application/json',
type : 'POST',
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
})
});
$("#check").click(function() {
$.ajax({
url: "http://localhost:8080/api/ping",
method: "GET",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
}
})
});
我面临的问题是我无法通过 $http 服务在 AngularJS 中使用它.我是这样试的:
The problem that I'm facing is that I can't get this to work in AngularJS with the $http service. I tried it like this:
$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}).
success(function(data) {
$location.path('/');
console.log(data);
}).
error(function(data, error) {
console.log(error);
});
谁能告诉我我做错了什么?
Can anyone tell me what I'm doing wrong?
推荐答案
你应该传递一个配置对象,就像这样
You should pass a configuration object, like so
$http.post(url, {withCredentials: true, ...})
或在旧版本中:
$http({withCredentials: true, ...}).post(...)
另见 你的其他问题.
这篇关于带凭据的 AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!