2012-12-06 13 views
38

Pracowałem nad projektem AngularJS, który musi wysyłać wywołania AJAX do restfull webservice. Ten serwis internetowy znajduje się w innej domenie, więc musiałem włączyć cors na serwerze. Zrobiłem to przez ustawienie tych nagłówków:AngularJS withCredentials

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"); 

jestem w stanie wysyłać żądań AJAX z angularjs do backend ale jestem w obliczu problemu, gdy próbuję uzyskać atrybut sesji. Sądzę, że dzieje się tak dlatego, że plik cookie sessionid nie jest wysyłany do backendu.

Byłem w stanie naprawić to w jQuery, ustawiając zCredentials na 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); 
     } 
    }) 
}); 

Problem, przed którym stoję, polega na tym, że nie mogę uruchomić tego w AngularJS z usługą $ http. Próbowałem tak:

$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); 
      }); 

Czy ktoś może mi powiedzieć, co robię źle?

Odpowiedz

61

Należy przekazać obiekt konfiguracji, tak jak

$http.post(url, {withCredentials: true, ...}) 

lub w starszych wersjach:

$http({withCredentials: true, ...}).post(...) 

Zobacz także your other question.

+8

+1 i jeśli używasz ngresource byś zadeklarować wywołanie metody z czymś w rodzaju '” getUserDetail ': {method:' GET ', params: {}, withCredentials: true} ' – ch4nd4n

+0

W tym przypadku tylko zCredentials: true idzie w tej formie lub też opcje Content-Type, Accept, crossDomain, Access-Control-Allow-Credentials/Origin/Headers? – wanttobeprofessional

+0

W tym przypadku starsza i nowsza wersja to? – wanttobeprofessional

46

W funkcji app config dodać to:

$httpProvider.defaults.withCredentials = true; 

To doda ten nagłówek dla wszystkich żądań.

Nie zapomnij, aby wstrzyknąć $httpProvider

EDIT: 2015-07-29

Oto inne rozwiązanie:

HttpIntercepter może być używany do dodawania wspólne nagłówki, jak również wspólne parametry.

Dodaj ten w config:

$httpProvider.interceptors.push('UtimfHttpIntercepter');

i stworzyć fabrykę o nazwie 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; 
}