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

I just want to send the following JSON objects to my API:

{ "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 the POST documentation that the Content-Type header will be automatically set to "application / json" .

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

This will cause my API to not respond correctly to this request. How do I manage this type of content?

+6
source share
2 answers

The solution I switched with is to always initialize the models on $ scope with the empty block {} on each controller. This ensures that if the data is not tied to this model, you will still have an empty block to go 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 binary || data statement when calling $ http.put or $ http.post to make sure that a specific argument is provided:

 $http.put("/users/current", data || {}).then(/* ... */); 
+2
source

Try it;

 $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 }); 
0
source

Source: https://habr.com/ru/post/952813/


All Articles