Angular,使用资源时未正确生成内容类型 [英] Angular, content type is not being generated correctly when using resource

查看:24
本文介绍了Angular,使用资源时未正确生成内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have tried the following command, using resource on 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".

but the http content type is not being generated correctly, in this case "application/json".

我见过类似的问题,例如 AngularJS 资源未设置 Content-Type,但我有最新的 Angular 版本 (1.0.6/1.1.4).

I have seen similar questions like AngularJS resource not setting Content-Type ,but I have the lastest Angular version (1.0.6/1.1.4).

上面的代码有什么问题?

What is wrong with the code above?

结论

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

推荐答案

查看 angular 源码, 1.1.4 版第 8742 行:

Look at the angular source, line 8742 in the version 1.1.4:

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

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

The Content-Type header gets removed if the request does not contain any data (a request body).

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

I think this is the expected behaviour since GET requests do not have a body.

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

A POST method in the other hand, will set the content-type as you expect, as long it has data in the request body. Try the following:

将方法改为POST

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

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

And call your resource action with some parameter:

Example.query(yourData)

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

In this case the content type is correctly set.

编辑:

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

It seems it also works with get, in this case the data is in the second parameter:

Example.query(yourParams, yourData)

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

这篇关于Angular,使用资源时未正确生成内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆