AngularJS с учетными данными
Я работал над проектом AngularJS, который должен отправлять AJAX-вызовы в исправную веб-службу. Этот веб-сервис находится в другом домене, поэтому мне пришлось включить 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);
});
Может кто-нибудь сказать мне, что я делаю не так?
2 ответа
Вы должны передать объект конфигурации, например, так
$http.post(url, {withCredentials: true, ...})
или в более старых версиях:
$http({withCredentials: true, ...}).post(...)
Смотрите также ваш другой вопрос.
В функции конфигурации вашего приложения добавьте это:
$httpProvider.defaults.withCredentials = true;
Он добавит этот заголовок для всех ваших запросов.
Не забудьте ввести $httpProvider
РЕДАКТИРОВАТЬ: 2015-07-29
Вот еще одно решение:
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;
}
Разъяснение:
$http.post(url, {withCredentials: true, ...})
должно быть
$http.post(url, data, {withCredentials: true, ...})