2012-12-06 4 views
38

저는 AJAX 호출을 편안한 웹 서비스에 보내야하는 AngularJS 프로젝트에서 작업 해 왔습니다. 이 웹 서비스는 다른 도메인에 있으므로 서버에서 cors를 활성화해야했습니다. 내가 백엔드에 AngularJS와에서 AJAX 요청을 보낼 수 있어요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"); 

하지만 난 세션의 속성을 얻을 때 나는 문제에 직면하고있어 : 나는이 헤더를 설정하여이했다. 나는 sessionid 쿠키가 백엔드로 보내지지 않기 때문에 이것이라고 생각한다.

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

누군가 내가 뭘 잘못하고 있는지 말해 줄 수 있니?

답변

61

당신은 너무

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

처럼 또는 이전 버전에서, 구성 개체를 전달해야합니다

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

your other question를 참조하십시오. 앱 설정 기능에서

+8

+1로하고 :

당신의 설정이 추가 – ch4nd4n

+0

이 경우에만 withCredentials : true가 해당 양식 또는 옵션 Content-Type, Accept, crossDomain, Access-Control-Allow-Credentials에 포함됩니다./오리진/헤더? – wanttobeprofessional

+0

이 경우 더 오래된 버전입니까? – wanttobeprofessional

46

이 추가 :

$httpProvider.defaults.withCredentials = true; 

그것은 모든 요청에 ​​대해이 헤더를 추가합니다.

말라 주입 잊지 $httpProvider

EDIT :

HttpIntercepter 공통 헤더뿐만 아니라 공통 파라미터를 추가 사용할 수있다 : 여기서

2015년 7월 29일 다른 해결책이다. 당신이 사용하는 경우는`같은 뭔가 메서드 호출을 선언 할 ngresource

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