AngularJS withCredentials [英] AngularJS withCredentials
问题描述
我一直工作在具有发送AJAX调用一个REST风格的web服务项目AngularJS。此WebService是另一个领域,所以我不得不在服务器上启用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");
我能够从AngularJS发送AJAX请求到后端,但我现在面临一个问题,当我试图让一个会话的属性。我相信这是因为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(...)
又见<一个href=\"http://stackoverflow.com/questions/13734686/communication-between-angularjs-and-a-jersey-webservice-which-are-on-a-different/14111039#14111039\">your另一个问题。
这篇关于AngularJS withCredentials的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!