我一直在研究AngularJS项目,该项目必须将AJAX调用发送到restfull webservice。这个web服务在另一个域上,所以我不得不在服务器上启用cors。我通过设置这些标题来完成此操作:
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没有发送到后端。
我可以通过将withCredentials设置为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中使用它。我试过这样的话:
$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);
});
谁能告诉我我做错了什么?
答案 0 :(得分:64)
您应该传递配置对象,如此
$http.post(url, {withCredentials: true, ...})
或旧版本:
$http({withCredentials: true, ...}).post(...)
答案 1 :(得分:50)
在你的应用配置功能中添加:
$httpProvider.defaults.withCredentials = true;
它将为您的所有请求附加此标头。
别忘了注入$httpProvider
这是另一种解决方案:
HttpIntercepter可用于添加公共标题以及常用参数。
在您的配置中添加:
$httpProvider.interceptors.push('UtimfHttpIntercepter');
并创建名称为UtimfHttpIntercepter
angular.module('utimf.services', [])
.factory('UtimfHttpIntercepter', UtimfHttpIntercepter)
UtimfHttpIntercepter.$inject = ['$q'];
function UtimfHttpIntercepter($q) {
var authFactory = {};
var _request = function (config) {
config.headers = config.headers || {}; // change/add hearders
config.data = config.data || {}; // change/add post data
config.params = config.params || {}; //change/add querystring params
return config || $q.when(config);
}
var _requestError = function (rejection) {
// handle if there is a request error
return $q.reject(rejection);
}
var _response = function(response){
// handle your response
return response || $q.when(response);
}
var _responseError = function (rejection) {
// handle if there is a request error
return $q.reject(rejection);
}
authFactory.request = _request;
authFactory.requestError = _requestError;
authFactory.response = _response;
authFactory.responseError = _responseError;
return authFactory;
}
答案 2 :(得分:0)
说明:
$http.post(url, {withCredentials: true, ...})
应该是
$http.post(url, data, {withCredentials: true, ...})