2013-08-30 97 views
6

我只想下面一个JSONObjects发送到我的API后端:

{ 
    "username":"alex", 
    "password":"password" 
} 

所以我写了下面的功能,采用了棱角分明的$ HTTP:

$http(
{ 
    method: 'POST', 
    url: '/api/user/auth/', 
    data: '{"username":"alex", "password":"alex"}', 
}) 
.success(function(data, status, headers, config) { 
// Do Stuff 
}) 
.error(function(data, status, headers, config) { 
// Do Stuff 
}); 

我读在POST方法Content-Type头将被自动设置为“应用程序/ JSON”文档。

但我意识到,我在我的后端(Django + Tastypie)api上收到的内容类型是“text/plain”

这会导致我的API无法正确响应此请求。我应该如何管理这种内容类型?

+0

您的后端如何检索细节? – BKM

+0

我使用Django Tastypie作为我的后端。我在$ http发送的内容类型中看到text/plain。 raw_post_data或POST数据也是空的。 –

+0

所以很奇怪......如果我把标题:{'Content-Type':'application/x-www-form-urlencoded; charset = UTF-8'}它工作..但是,如果我把应用程序/ JSON ...它不是... –

回答

0

试试这个;

$http.defaults.headers.post["Content-Type"] = "application/json"; 

$http.post('/api/user/auth/', data).success(function(data, status, headers, config) { 
// Do Stuff 
}) 
.error(function(data, status, headers, config) { 
// Do Stuff 
}); 
2

我前进的解决方案是始终将$ scope上的模型初始化为每个控制器上的空块{}。这保证了如果没有数据绑定到那个模型,那么你仍然有一个空的块传递给你的$ http.put或$ http.post方法。

myapp.controller("AccountController", function($scope) { 
    $scope.user = {}; // Guarantee $scope.user will be defined if nothing is bound to it 

    $scope.saveAccount = function() { 
     users.current.put($scope.user, function(response) { 
      $scope.success.push("Update successful!"); 
     }, function(response) { 
      $scope.errors.push("An error occurred when saving!"); 
     }); 
    }; 
} 

myapp.factory("users", function($http) { 
    return { 
     current: { 
      put: function(data, success, error) { 
       return $http.put("https://stackoverflow.com/users/current", data).then(function(response) { 
        success(response); 
       }, function(response) { 
        error(response); 
       }); 
      } 
     } 
    }; 
}); 

另一种选择是使用二进制||操作员在调用$ http.put或$ http.post以确保提供已定义的参数时的数据:

$http.put("https://stackoverflow.com/users/current", data || {}).then(/* ... */);