Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON using $http cause angular to send text/plain content type

I just want to send the following JSONobjects to my API backend:

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

So I wrote the following function, using 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
});

I read in documentation for POST method that Content-Type header will be automatically set to "application/json".

But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".

This cause my API to not respond properly to this request. How should I manage this content-type?

like image 978
Alex Grs Avatar asked Aug 30 '13 08:08

Alex Grs


1 Answers

The solution I've moved forward with is to always initialize models on the $scope to an empty block {} on each controller. This guarantees that if no data is bound to that model then you will still have an empty block to pass to your $http.put or $http.post method.

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

Another alternative is to use the binary || operator on data when calling $http.put or $http.post to make sure a defined argument is supplied:

$http.put("/users/current", data || {}).then(/* ... */);
like image 77
Erik Gillespie Avatar answered Sep 30 '22 14:09

Erik Gillespie