【问题标题】:Sending JSON using $http cause angular to send text/plain content type使用 $http 发送 JSON 导致 Angular 发送文本/纯内容类型
【发布时间】:2013-09-02 21:33:36
【问题描述】:

我只想将以下 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
});

我在 POST 方法的文档中读到 Content-Type 标头将自动设置为 "application/json"

但我意识到我在后端 (Django+Tastypie) api 上收到的内容类型是 "text/plain"

这会导致我的 API 无法正确响应此请求。我应该如何管理这种内容类型?

【问题讨论】:

  • 您的后端如何检索详细信息?
  • 我使用 Django Tastypie 作为后端。我在 $http 发送的内容类型中看到 text/plain。 raw_post_data 或 POST 数据也是空的。
  • 太奇怪了...如果我放标题:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'} 它正在工作.. 但是如果我把 application/json... 它不是...
  • 我也看到了这种行为。当数据块为空时,Angular 似乎忽略了默认的“application/json”并将 Content-Type 设置为“plain/text”。在 $http 上显式设置默认值或将 Content-Type 设置为 put() 调用的参数似乎都没有任何效果。我正在使用 AngularJS 1.2.0。
  • 您是否通过配置阶段设置标题?

标签: javascript django angularjs tastypie


【解决方案1】:

试试这个;

$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】:

    我提出的解决方案是始终将 $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);
                    });
                }
            }
        };
    });
    

    另一种选择是使用二进制 ||调用 $http.put 或 $http.post 以确保提供定义的参数时对数据的运算符:

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

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多