使用资源时,未正确生成Angular内容类型

时间:2013-04-24 20:51:05

标签: angularjs

我在Angular上使用资源尝试了以下命令:

angular.module('appServices', ['ngResource']).factory('Example', 
        function($resource){

            return $resource('http://api.example.com.br/teste', {}, {
                query: {method:'GET', headers: {'Content-Type': 'application/json'}}
        });
});

但是http内容类型没有正确生成,在本例中为“application / json”。

我见过像AngularJS resource not setting Content-Type这样的类似问题,但我有最新的Angular版本(1.0.6 / 1.1.4)。

上面的代码出了什么问题?

结论

  • 如下所述,HTTP Get方法不应该有正文。
  • 属性标题在上述版本中不起作用。我使用以下命令失败: 查询:{方法:'POST',标题:{'Content-Type':'application / json'}}
  • 这种方式对我有用: $ http.defaults.headers.put ['Content-Type'] ='application / json';

2 个答案:

答案 0 :(得分:15)

查看版本1.1.4中的angular source,第8742行:

  // strip content-type if data is undefined
  if (isUndefined(config.data)) {
    delete reqHeaders['Content-Type'];
  }

如果请求不包含任何数据(请求正文),则会删除Content-Type标头。

我认为这是预期的行为,因为 GET请求没有正文

另一方面,POST方法将按预期设置内容类型,只要它在请求正文中有数据。请尝试以下方法:

将方法更改为POST

query: {method:'POST', headers: {'Content-Type': 'application/json'}}

使用一些参数调用您的资源操作:

Example.query(yourData)

在这种情况下,内容类型已正确设置。

修改

似乎它也适用于get,在这种情况下数据位于第二个参数:

Example.query(yourParams, yourData)

示例:http://jsfiddle.net/WkFHH/

答案 1 :(得分:0)

看起来仍然不受支持 - 如果你必须设置标题,可以使用$http service