6

我只想将以下 JSONobjects 发送到我的 API 后端:

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

所以我编写了以下函数,使用 Angular $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 标头将自动设置为"application/json"

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

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

4

2 回答 2

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("/users/current", data).then(function(response) {
                    success(response);
                }, function(response) {
                    error(response);
                });
            }
        }
    };
});

另一种选择是使用二进制 || 调用 $http.put 或 $http.post 以确保提供定义的参数时对数据的运算符:

$http.put("/users/current", data || {}).then(/* ... */);
于 2013-11-13T20:46:56.553 回答
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
});
于 2013-08-30T08:21:45.793 回答