使用资源时没有被正确生成的角度,内容类型 [英] Angular, content type is not being generated correctly when using resource
问题描述
我曾尝试下面的命令,使用对角资源:
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内容类型,在这种情况下,应用/ JSON
but the http content type is not being generated correctly, in this case "application/json".
我见过像<一个类似的问题href=\"http://stackoverflow.com/questions/12785386/angularjs-resource-not-setting-content-type\">AngularJS资源不设置Content-Type的的,但我必须介绍最新版本角(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).
什么是错的code以上?
What is wrong with the code above?
结论
- 正如前面提到的波纹管,HTTP GET方法不应该有一个机构。
- 的属性标题中不上述版本。我用失败下面的命令:
查询:{方法:POST,标题:{内容类型:应用/ JSON'}} - 这种方式很适合我:
$ http.defaults.headers.put ['内容类型'] ='应用/ JSON';
推荐答案
看角源,符合8742版1.1.4:
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'];
}
如果请求不包含任何数据(请求主体)。
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.
修改
看来它也可以与获取,在这种情况下,数据是在第二个参数:
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/
这篇关于使用资源时没有被正确生成的角度,内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!