我一直在开发一个 AngularJS 项目,该项目必须将 AJAX 调用发送到 Restfull Web 服务。该网络服务位于另一个域中,因此我必须在服务器上启用 cors。我通过设置这些 header 来做到这一点:
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 发送到后端,但当我尝试获取 session 的属性时遇到问题。我相信这是因为 sessionid cookie 没有发送到后端。
我可以通过将 withCredentials 设置为 true 在 jQuery 中修复此问题。
$("#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 中使用它。我尝试过这样的:
$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);
});
谁能告诉我我做错了什么?
请您参考如下方法:
您应该传递一个配置对象,如下所示
$http.post(url, {withCredentials: true, ...})
或者在旧版本中:
$http({withCredentials: true, ...}).post(...)
另请参阅your other question .