Paul
Paul

Reputation: 26660

How to specify dataType: 'json' in Angular.js $http.post?

I would like to specify dataType: 'json' as in conventional jQuery $.ajax. Is this possible with Angular.js $http.post ?

Upvotes: 14

Views: 53983

Answers (3)

Mulaffer
Mulaffer

Reputation: 661

I had the same problem, responseType:'json' solved the issue

You can use responseType:'json' instead of dataType:'json'

var promise = $http({
            method: 'POST',
            url: 'somewhere.xyz',
            responseType:'json'

        });

For further reference https://docs.angularjs.org/api/ng/service/$http#methods_jsonp

Upvotes: 4

Jason Aden
Jason Aden

Reputation: 2823

You can use the HTTP Config object to set the headers:

$http({
    method: 'POST',
    url: 'somewhere.xyz',
    headers: {
        'Content-type': 'application/json'
    }
})

Upvotes: 20

Musa
Musa

Reputation: 97672

From http://docs.angularjs.org/api/ng.$http

Transforming Requests and Responses Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:

Request transformations:

  • if the data property of the request config object contains an object, serialize it into JSON format. Response transformations:

  • if XSRF prefix is detected, strip it (see Security Considerations section below)

  • if json response is detected, deserialize it using a JSON parser

So no need to set a data type it is done automatically

Upvotes: 5

Related Questions