1

I'm struggling to get AngularJS to set the HTTP Content-Type header to application/json. I've seen that it's often done as such:

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

But this doesn't seem to do it. Inspecting the headers in Chrome, I don't see any Content-Type header:

Screenshot from Google Chrome

I've been able to get the request to work in POSTMAN, with the following settings:

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

Any thoughts? What am I am doing wrong here?

charlierproctor
  • 1,132
  • 9
  • 11

3 Answers3

1

Try to modify your CORS settings on the server as follows:

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

axon
  • 4,081
  • 1
  • 12
  • 14
0

Here's an example for alpha build 46

var queryParams = JSON.stringify(this.testProfile);

    var queryHeaders = new Headers();
    queryHeaders.append('Content-Type', 'application/json');


    this.http.post('/api/DataReference/TestProfiles/UpdateTestProfile', queryParams, { headers: queryHeaders})
        .subscribe(res => {
            alert('Object Updated');
        });
Andrew Walters
  • 4,763
  • 6
  • 35
  • 49
-1

Do you really need to set the content type for JSON?

Below i have given a code snippet, this how i have followed to post the data in a struts application, perhaps it would solve your problem.

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);
       });
};
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Arun
  • 1,010
  • 6
  • 18
  • 37
  • That doesn't seem to work either. To my understanding, 'application/x-www-form-urlencoded' and 'application/json' are different content types. – charlierproctor Sep 20 '15 at 05:32