【问题标题】:Angular, content type is not being generated correctly when using resource使用资源时未正确生成角度内容类型
【发布时间】:2013-04-18 14:10:46
【问题描述】:

我已经尝试了以下命令,使用 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';

【问题讨论】:

  • 正如@gargc 还问的那样,您确定不想设置“接受”标头吗?在这里设置 Content-Type 想要达到什么目的?

标签: angularjs


【解决方案1】:

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

【讨论】:

【解决方案2】:

angular source,1.1.4版本第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/

【讨论】:

  • 好吧,你是对的。我尝试使用 post 和 Example.query("test"),内容类型工作得很好,但我应该怎么做才能更改“Get”内容类型?我做了同样的事情,Example.query("test") 和 Example.query(""),仍然没有工作。
  • 但是为什么需要为 GET 请求设置内容类型呢?请求中没有正文/有效负载,参数在 url 中。 Accept 标题可能是您想要的吗?
  • 无论如何,我已经意识到将数据作为函数的第二个参数传递适用于 GET 并防止内容类型被删除。 (答案已编辑)
  • 您也可以通过在资源配置中添加一个空数据属性来使其工作(恕我直言):angular.module('appServices', ['ngResource']).factory('Example', function($resource){ return $resource('http://api.example.com.br/teste', {}, { query: { data: '', method:'GET', headers: {'Content-Type': 'application/json'} } }); });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 2019-12-13
  • 1970-01-01
  • 2015-05-22
  • 2016-05-10
  • 2014-09-15
  • 1970-01-01
相关资源
最近更新 更多