2017-02-11 214 views
0

我正在構建一個帶有Django Rest Framework API後端的單頁Web應用程序。我有問題發送註冊表單。我認爲格式化日期的方式存在問題。 這裏的控制器的樣子:在http發佈請求期間angularjs 400錯誤請求

(function() { 
'use strict'; 

angular 
    .module('CityWits') 
    .controller('standardController', standardController); 

standardController.$inject = ['UserService','$location', '$rootScope', 'FlashService']; 
function standardController(UserService, $location, $rootScope, FlashService) { 
    var vm = this; 

    vm.standard = standard; 

    function standard() { 
     vm.dataLoading = true; 

     var str = []; 
     for(var p in vm.user){ 
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(vm.user[p])); 
     } 
     str = str.join("&"); 

     UserService.CreateStandard(vm.user) 
      .then(function (response) { 
       if (response.success) { 
        FlashService.Success('Registration successful', true); 
        $location.path('/sign-in'); 
       } else { 
        alert(response.message) 
        vm.dataLoading = false; 
       } 
      }); 
    } 

    function fixDate(date){ 


    } 
} 

})();

崗位要求:

function CreateStandard(user) { 
     console.log(user) 
     return $http.post('http://127.0.0.1:8000/api/users/standard', user).then(handleSuccess, handleError('Error creating user')); 
    } 

JSON對象正在從形式發送:

Object 

DATE_OF_BIRTH : 星期五1993年8月6日00:00:00 GMT-0400(東部夏令時間) 名字 : 「David」 性別 : 「M」 姓氏 : 「加洛韋」 用戶 : 對象 電子郵件 : 「[email protected]」 密碼 : 「*******」 : 對象 : 對象

回答

0

如果要發佈爲JSON字符串,則必須將HTTP標頭「內容類型」設置爲JSON。

否則,數據需要在應用程序/ x-WWW窗體-urlencoded,這意味着這樣的形式:參數=值&也=另一

這被高亮顯示here在DRF DOC:

注:在開發客戶端應用程序永遠記住,以確保 你發送數據時設置Content-Type頭在HTTP 請求中。

如果您沒有設置內容類型,大多數客戶將默認使用 'application/x-www-form-urlencoded',這可能不是您想要的。例如,如果您使用jQuery和 .ajax()方法發送json編碼數據,則應確保包含contentType: 'application/json'設置。

坦率地說,JSON是更清晰的看到,所以我會做的是:

function CreateStandard(user) { 
    return $http({ 
     method: 'POST', 
     url: 'http://127.0.0.1:8000/api/users/standard', 
     data: JSON.stringify(user), 
     headers: {"Content-Type": "application/json"} 
    }).then(...); 
} 
0

使用JSON.stringify發送user對象:

function CreateStandard(user) { 
    console.log(user) 
    return $http.post('http://127.0.0.1:8000/api/users/standard', JSON.stringify(user)) 
       .then(handleSuccess, handleError('Error creating user')); 
} 
+0

試了一下,它仍在發送回400錯誤的請求 –