2013-08-30 30 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(/* ... */);