我正在使用 $http
执行 GET 请求,我想在 header 中附加 'Content-Type': 'application/json'
。如果我不附加此 header ,则会引发 415(不支持的媒体类型)
错误。
我将 Apache 2.2.13 与 ProxyPass 一起使用,其中我不说
RequestHeader 附加内容类型“application/json”
。但是,如果我将 RequestHeader
配置放在 apache $http.get
中,则可以正常工作,并且还会附加 'Content-Type'
。
场景 1:
使用 $http
,尝试 GET 请求
请求:
$http({
method: 'GET',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
Chrome 网络选项卡:
场景 2:
使用 Restangular
,尝试相同的 GET 请求
请求:
Restangular.setDefaultHeaders({'Content-Type': 'application/json'})
Restangular.setBaseUrl('/items')
Restangular.all('').getList({customerId: '103020'}, {'Content-Type': 'application/json'});
Chrome 网络选项卡:
这里另一个有趣的部分是,当我在请求 header 上犯了一些错误,比如,
Restangular.setDefaultHeaders({'Contenttt-Type': 'application/json'})
并尝试方案 1,我在 Chrome 网络选项卡中注意到以下内容。
场景 3:
使用 jQuery
ajax,尝试相同的 GET 请求
请求:
$.ajax({
url: "/items/?customerId=103020",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Content-Type', 'application/json');},
success: function() { alert('Success!'); }
});
Chrome 网络选项卡:
问题:
- 是否需要在Apache配置中添加
RequestHeader append Content-Type "application/json"
?但是,如果我添加它,我会在POST
请求中收到 415 错误。 - AngularJS 和 Restangular 有什么问题,它不会将
Content-Type
header 附加到其GET
上的网络调用? - 解决这个问题的最佳方案是什么?我已经尝试了所有的组合,但没有成功!
版本:
Angular :1.2.22
重新排列:1.4.0
最佳答案
一方面,使用 $http
服务,您可以在调用 config
方法时使用 $httpProvider
覆盖或添加 header 在你的模块上:
module.config(function($http) {
$httpProvider.defaults.headers.get = { 'Content-Type : 'application/json' };
});
另一方面,对于 GET
方法,如果您的 API 真的是 RESTFull,则只应设置 Accept
header ,因为您没有发送 JSON
数据。
因此,将上述代码用于您的PUT
/POST
方法并强制GET
的Accept
header >方法:
module.config(function($http) {
$httpProvider.defaults.headers.post = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.put = { 'Content-Type : 'application/json'};
$httpProvider.defaults.headers.get = { 'Accept : 'application/json'};
});
编辑 1:
如果你想在 GET
请求中强制使用 content-type
,你必须添加一个空白数据:
$http({
method: 'GET',
data:'',
dataType:'json',
headers: { 'Content-type': 'application/json'},
url: '/items/?customerId=5656'
});
关于angularjs - $http header 'Content-Type' 未附加在 header 中 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35035257/