AngularJS没有设置内容类型' :' application / json'

时间:2015-09-20 04:36:34

标签: json angularjs http-headers

我很难让AngularJS将HTTP Content-Type标头设置为application/json。我已经看到它经常这样做了:

    $http({
        method: 'POST',
        url: 'http://myurl.com',
        data: {
            "key":"value"
        },
        headers : {
            'Content-Type' : 'application/json'
        }
    })

但这似乎并没有。检查Chrome中的标题,我看不到任何Content-Type标题:

Screenshot from Google Chrome

我已经能够通过以下设置获得在POSTMAN中工作的请求:

POST /run HTTP/1.1
Host: myurl.com:80
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 5470283d-0f71-93a0-32ff-cc2fa4395eaa

{
    "key" : "value"
}

有什么想法?我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试按如下方式修改服务器上的CORS设置:

'Access-Control-Allow-Headers': 'Accept, Content-Type'

答案 1 :(得分:-1)

您真的需要为JSON设置内容类型吗?

下面我给出了一个代码片段,这是我如何跟踪在struts应用程序中发布数据,也许它可以解决你的问题。

Angularjs-Post

$scope.postData = function() {

     var data = escape(angular.toJson($scope.items));

     console.log(data);        

     $http({
          method: 'POST',
          url: '/StrutsWithAngular/shopingCart.do',
          data: 'cartValues='+data,
          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
       }).success(function(data, status, headers, config) {
            $scope.items = data;
       }).error(function(data, status, headers, config) {
        // alert("Error :: "+data);
       });
};
相关问题