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
});

Content-Type ヘッダーが自動的に"application/json"に設定されるという POST メソッドのドキュメントを読みました。

しかし、バックエンド (Django + Tastypie) API で受け取る content-type が"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);
                });
            }
        }
    };
});

もう 1 つの方法は、バイナリ || を使用することです。$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 に答える