2014-12-16 10 views
-2

프런트 엔드에는 AngularJS를, 작업중인 웹 응용 프로그램의 백엔드에는 Django를 사용하고 있습니다. 지금은 사용자 로그인 문제를 겪고 있으며 이상한 문제가 있습니다. Heres는 관련 각도 코드 : 여기AngularJS/Django Post 응답 데이터

app.factory('AuthService', ["$http", "$q", "Session", "URL", function($http, $q, Session, URL) { 
return { 

login: function(credentials) { 
    var deferred = $q.defer(); 
    $http.post(URL.login, credentials) 
      .then(function(data, status, headers, config) { 
       data=data.data; //WHY DOES THIS WORK? 
       if (data.success == true) { 
       alert("logged in"); 
       Session.create(credentials.username, data.api_key); 
       deferred.resolve(); 
       } 
       else { 
       deferred.reject("Login failed!"); 
       } 
      }, function(data, status, headers, config) { 
       deferred.reject("Login failed!"); 
      }); 
    return deferred.promise 
}, 

그리고는 해당 장고이다 :

POST 요청에서 사용자가 로그인 장고 위의 코드에 의해 전송 및 처리
def login_user(request): 
    ''' 
    Given a username and password, returns the users API key. 
    ''' 
    if request.method == 'POST': 
     username = request.POST.get('username',None) 
     password = request.POST.get('password',None) 
     user = authenticate(username=username,password=password) 
     if user is not None: 
      api_key = ApiKey.objects.get(user=user) 
      response_data = {} 
      response_data["api_key"] = str(api_key).split(" ")[0] 
      response_data["success"] = True 
      return HttpResponse(json.dumps(response_data), content_type="application/json") 
     else: 
      return HttpResponse(json.dumps({"username":username,"success":False}),content_type="application/json") 
    return HttpResponseBadRequest() 

. 응답은 위의 AngularJS 코드에 의해 선택됩니다. 보시다시피 Angular 코드의 then() 메소드는 일반적인 네 개의 매개 변수 (데이터, 상태, 구성 및 헤더)를 사용합니다. 나는 데이터가 장고 코드의 사전 결과를 포함하고, 적절하게 JSON 객체로 직렬화 될 것을 기대한다.

그러나 어떻게됩니까? undefined가 아닌 then() 메서드의 유일한 매개 변수는 데이터이며 여기에는 모든 요소가 포함됩니다. 헤더, 데이터, 상태 코드 등.

이 줄은 내부에서 데이터에 액세스하여 '이 작업이 왜 이루어지는가?'라는 문제를 해결했습니다. 그러나 나는 이것이 왜 일어나고 있는지, 그리고 이것을 피할 수있는 방법이 있는지 알고 싶다. 내 최고의 추측은 장고가 응답을 직렬화하는 방식과 관련이 있지만 잘 모르겠습니다.

장고 1.6.5를 사용하고 있습니다.

+0

이 글을 읽는 것이 좋습니다. https://thinkster.io/django-angularjs-tutorial – mrvol

답변

0

Angular promises가 실제로 작동하는 방법은 according to the docs입니다. 여기에 관련 인용문이 있습니다.

은 $ HTTP 함수를 호출의 반환 값은 약속이기 때문에, 당신은 또한 콜백을 등록하려면 다음 방법을 사용할 수 있으며, 이러한 콜백이 하나의 인자를받을 것이다 - 를 나타내는 객체를 응답. 자세한 내용은 아래 API 서명 및 유형 정보를 참조하십시오.

중점은 내 것이 었습니다.

+0

죄송합니다. 저는 Angular를 처음 사용합니다. 도와 주셔서 감사합니다 :) – MichaelJK