Ответ 1
Вы должны передать объект конфигурации, например
$http.post(url, {withCredentials: true, ...})
или в более ранних версиях:
$http({withCredentials: true, ...}).post(...)
См. также ваш другой вопрос.
Я работаю над проектом AngularJS, который должен отправлять вызовы AJAX в restfull webservice. Этот веб-сервис находится в другом домене, поэтому мне пришлось включить 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");
Я могу отправить запросы AJAX из AngularJS на бэкэнд, но у меня возникла проблема, когда я пытаюсь получить атрибут сеанса. Я считаю, что это связано с тем, что cookie sessionid не отправляется на сервер.
Мне удалось исправить это в jQuery, установив 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);
}
})
});
Проблема, с которой я столкнулась, заключается в том, что я не могу заставить это работать в AngularJS с помощью сервиса $http. Я пробовал это следующим образом:
$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(...)
См. также ваш другой вопрос.
В вашей конфигурации приложения добавьте следующее:
$httpProvider.defaults.withCredentials = true;
Он добавит этот заголовок для всех ваших запросов.
Не забудьте ввести $httpProvider
Вот еще одно решение:
HttpIntercepter может использоваться для добавления общих заголовков, а также общих параметров.
Добавьте это в свою конфигурацию:
$httpProvider.interceptors.push('UtimfHttpIntercepter');
и создайте factory с именем 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;
}
Разъяснение:
$http.post(url, {withCredentials: true, ...})
должно быть
$http.post(url, data, {withCredentials: true, ...})