2013-08-30 12 views
6

metin/düz içerik türü göndermek için açısal neden: Açısal $ http,

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

yüzden aşağıdaki işlevi yazdı:

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

Ben Content-Type başlığı otomatik "application/json" olarak ayarlanır POST yöntemi için belgelerinde okundu.

Ancak arka uçta (Django + Tastypie) api aldığım içerik türünün "text/plain" olduğunu farkettim.

Bu, API'mın bu isteğe yanıt vermemesine neden oluyor. Bu içerik türünü nasıl yönetmeliyim?

+0

Arka uçunuz ayrıntıları nasıl alıyor? – BKM

+0

Arka Uçum için Django Tastypie kullanıyorum. İçerik türünde $ http tarafından gönderilen metin/düz görüyorum. raw_post_data veya POST verileri de boş. –

+0

Çok garip ... Eğer başlıkları koyarsam: {'Content-Type': 'application/x-www-form-urlencoded; charset = UTF-8 '} çalışıyor .. Ama eğer uygulamayı/jsonu koyarsam ... bu değil ... –

cevap

0

Bunu deneyin;

$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

Hep her denetleyici üzerinde boş bloğa {} için $ kapsamına modelleri başlatmak için olduğunu öne taşındım çözüm. Bu, bu modele hiçbir veri bağlı değilse, hala $ http.put veya $ http.post yönteminize geçmek için boş bir bloğunuzun olacağını garanti eder.

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

Başka bir alternatif ikili kullanmaktır || tanımlı bir argümanın sağlandığından emin olmak için $ http.put veya $ http.post çağrılırken operatöre bilgi verin:

$http.put("https://stackoverflow.com/users/current", data || {}).then(/* ... */); 
İlgili konular