我只想下面一个JSONObjects发送到我的API后端:
I just want to send the following JSONobjects to my API backend:
{
"username":"alex",
"password":"password"
}
所以我写了下面的功能,采用了棱角分明的$ HTTP:
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
});
我在POST方法Content-Type头会被自动设置为应用/ JSON
但我意识到,内容类型我收到我的后端(Django的+ Tastypie)API为text / plain的
But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".
这导致我的API无法正常响应该请求。我应如何管理这种内容类型?
This cause my API to not respond properly to this request. How should I manage this content-type?
我已经向前迈进,是要始终初始化在$范围机型为空块{}每个控制器上的解决方案。这保证了如果没有数据绑定到模型,那么你将仍然有一个空块传递到$ http.put或$ http.post方法。
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);
});
}
}
};
});
另一种选择是使用二进制||调用$当数据运营商http.put或$ http.post以确保规定的参数提供:
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(/* ... */);