6

我尝试了以下命令,使用 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 资源没有设置 Content-Type,但我有最新的 Angular 版本(1.0.6/1.1.4)。

上面的代码有什么问题?

结论

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

2 回答 2

15

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

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

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

我认为这是预期的行为,因为GETrequests 没有 body

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

将方法更改为POST

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

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

Example.query(yourData)

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

编辑

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

Example.query(yourParams, yourData)

一个例子:http: //jsfiddle.net/WkFHH/

于 2013-04-24T22:53:45.077 回答
0

看起来它仍然不受支持 - 如果您必须设置标头,您可以使用$http 服务

于 2013-04-24T21:20:00.327 回答