$http header 'Content-Type' 未附加到 header - AngularJS

$http header 'Content-Type' not appending in the header - AngularJS

我正在使用 $http 执行 GET 请求,我想在 header 中附加 'Content-Type': 'application/json'。如果我不附加此 header 415 (Unsupported Media Type) 错误将被抛出。

我正在使用 Apache 2.2.13 和 ProxyPass,其中 我不RequestHeader append Content-Type "application/json"。但是,如果我将 RequestHeader 配置放在 apache 中,$http.get 工作正常并且 'Content-Type' 也被附加。

场景一: 使用 $http,尝试 GET 请求

要求:

$http({
    method: 'GET',
    headers: { 'Content-type': 'application/json'},
    url: '/items/?customerId=5656'
});

Chrome 网络选项卡:


场景二: 使用 Restangular,尝试相同的 GET 请求

要求:

Restangular.setDefaultHeaders({'Content-Type': 'application/json'})
Restangular.setBaseUrl('/items')
Restangular.all('').getList({customerId: '103020'}, {'Content-Type': 'application/json'});

Chrome 网络选项卡:

这里另一个有趣的部分是,当我在请求 Header 上犯了一些错误,比如
Restangular.setDefaultHeaders({'Contentttt-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 网络选项卡:

问题:

  1. 是否需要在Apache配置中添加RequestHeader append Content-Type "application/json"?但是如果我添加我在 POST 请求上得到 415 个错误。
  2. AngularJS 和 Restangular 有什么问题,它不会将 Content-Type headers 附加到它在 GET 上的网络调用?
  3. 解决这个问题的最佳方案是什么?我已经尝试了所有的组合,但没有成功!

版本:

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 方法并强制 Accept header 用于 GET 方法:

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'
});

在没有请求body(例如GET)的HTTP请求上设置Content-Typeheader字段是non-sense.

也许您真正想要的是"Accept"?