Angular,内容类型不与$ http一起发送

时间:2013-04-24 14:19:00

标签: angularjs

Angular没有添加正确的内容类型选项,我尝试了以下命令:

$http({
    url: "http://localhost:8080/example/teste",
    dataType: "json",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

上面的代码生成以下http请求:

POST http://localhost:8080/example/teste HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/xml
Accept: application/json, text/plain, */*
X-Requested-With: XMLHttpRequest
Referer: http://localhost:8080/example/index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=C404CE2DA653136971DD1A3C3EB3725B

如您所见,内容类型不是“application / json”,而是“application / xml”。我在这里错过了什么吗?

6 个答案:

答案 0 :(得分:90)

您需要在请求中包含一个正文。 Angular会删除内容类型标题。

data: ''添加到$http的参数。

答案 1 :(得分:30)

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

试试这样。

答案 2 :(得分:4)

         $http({
                method: 'GET',
                url:'/http://localhost:8080/example/test' + toto,
                data: '',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(
                function(response) {
                    return response.data;
                }, 
                function(errResponse) {
                    console.error('Error !!');
                    return $q.reject(errResponse);
                }

答案 3 :(得分:2)

大!上面给出的解决方案对我有用。 GET来电时遇到同样的问题。

 method: 'GET',
 data: '',
 headers: {
        "Content-Type": "application/json"
 }

答案 4 :(得分:2)

如果它对任何人都有用。对于AngularJS 1.5x,我想为所有请求设置CSRF,我发现当我这样做时:

$httpProvider.defaults.headers.common = { "Content-Type": "application/json"};

Angular删除了内容类型,因此我不得不添加:

angular.module("myapp.maintenance", [])
    .controller('maintenanceCtrl', MaintenanceCtrl)
    .directive('convertToNumber', ConvertToNumber)
    .config(configure);

MaintenanceCtrl.$inject = ["$scope", "$http", "$sce", "$window", "$document", "$timeout", "$filter", 'alertService'];
configure.$inject = ["$httpProvider"];

// configure the header tokens for  CSRF for http operations in this module
function configure($httpProvider) {

    const afToken = angular.element('input[id="__AntiForgeryToken"]').attr('value');

    $httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; // only added for GET
    $httpProvider.defaults.headers.put = { 'CSRF-Token': afToken }; // added for PUT
    $httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; // added for POST

    // for some reason if we do the above we have to set the default content type for all 
    // looks like angular clears it when we add our own headers
    $httpProvider.defaults.headers.common = { "Content-Type": "application/json" };

}

否则我收到415媒体类型错误。

所以我这样做是为所有请求配置我的应用程序:

E1 << E2

答案 5 :(得分:0)

仅显示如何为每个POST请求动态添加“Content-type”标头的示例。在可能的情况下,我将POST params作为查询字符串传递,这是使用 transformRequest 完成的。在这种情况下,其值为 application / x-www-form-urlencoded

// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
    $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}

然后从请求方法中的拦截器返回配置对象

// if header['Content-type'] is a POST then add data
'request': function (config) {
  if (
    angular.isDefined(config.headers['Content-Type']) 
    && !angular.isDefined(config.data)
  ) {
    config.data = '';
  }
  return config;
}