繁体   English   中英

$ http标题'Content-Type'没有附加在标题中 - AngularJS

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

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

我正在使用带有ProxyPass的Apache 2.2.13,其中我不要RequestHeader append Content-Type "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网络标签:

在此输入图像描述

另一个有趣的部分是,当我在Request 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标题附加到GET上的网络调用中?
  3. 解决这个问题的最佳解决方案是什么? 我尝试了所有的组合,但没有运气!

版本:

Angular:1.2.22

Restangular:1.4.0

一方面,使用$http服务,您可以在调用模块上的config方法时使用$httpProvider覆盖或添加标头:

module.config(function($http) {
  $httpProvider.defaults.headers.get = { 'Content-Type : 'application/json' };
});

另一方面,使用GET方法,如果您的API确实是RESTFull,则只应设置Accept标头,因为您没有发送JSON数据。

因此,对PUT / POST方法使用上面的代码并强制GET方法的Accept标头:

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

在没有请求主体(例如GET)的HTTP请求上设置Content-Type头字段是没有意义的。

也许你真正想要的是设置“接受”?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM