61

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”。我在这里错过了什么吗?

4

6 回答 6

96

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

将参数添加data: ''$http.

于 2013-04-24T14:49:15.103 回答
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;
});

像这样试试。

于 2013-04-24T16:05:40.010 回答
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);
                }
于 2016-04-28T14:20:30.207 回答
2

伟大的!上面给出的解决方案对我有用。打电话也有同样的问题GET

 method: 'GET',
 data: '',
 headers: {
        "Content-Type": "application/json"
 }
于 2015-09-19T02:59:15.687 回答
2

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

$httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; 
$httpProvider.defaults.headers.put = { 'CSRF-Token': afToken };
$httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; 

Angular 删除了内容类型,所以我不得不添加:

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

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

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

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" };

}
于 2017-11-29T15:29:06.607 回答
0

只是为了展示如何将“Content-type”标头动态添加到每个 POST 请求的示例。在可能的情况下,我将 POST 参数作为查询字符串传递,这是使用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;
}
于 2017-11-17T21:14:30.370 回答