2017-02-11 216 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错误的请求 –