0

Coming from jQuery, setting the content-type to application/json would give me a json object instead of an xml-formatted string.

How can I achieve the same using AngularJS $http.post?

Tried doing

$http({
    method: "post",
    url: "url",
    headers: { "Content-Type": "application/json; charset=utf-8" }
})

but the parameter in success is an xml-formatted string.

Sharon Dorot
  • 542
  • 1
  • 4
  • 15
  • what data are you posting? – ForgetfulFellow Feb 25 '15 at 15:29
  • None, no parameters for the function – Sharon Dorot Feb 25 '15 at 15:30
  • http://stackoverflow.com/questions/16194442/angular-content-type-is-not-being-sent-with-http – ForgetfulFellow Feb 25 '15 at 15:33
  • That should answer your question perfectly – ForgetfulFellow Feb 25 '15 at 15:34
  • @SharonJDDorot FWIW, this says to me that the server side code is built improperly. The `Content-Type` header is for the _client_ to tell the _server_ what kind of content the client is _sending_. It is not for requesting a particular form of data in the response. Angular is completely correct to remove the `Content-Type` header of a request if no body is included in the request. No body = No content = no content type. – JAAulde Feb 25 '15 at 15:39
  • I suppose it is because it is a c# web service and it returns an object and microsoft supports xml natively. I did try attributes and such but no luck in that – Sharon Dorot Feb 25 '15 at 15:48

2 Answers2

1

Set "Content-Type" header to tell the server which type of content the request body contain and set "Accept" header to tell the server in which format you are expecting the content of the response body.

So if your server is able is render response in json format, then set the header "Accept : application/json" in your request.

headers: { "Content-Type": "application/json", "Accept" : "application/json" }

You can also verify the what request your angular app is sending and what response it is getting back from browser's development console.

Hope it will help you.

Manmay
  • 835
  • 7
  • 11
0

Just make the method: "post" and send an empty data object...

$http({
        method: "post",
        url: 'url',
        data: {}
    }).then( function(response) {
        console.log(response);
});

and if you want XML back:

$http({
        method: "post",
        url: 'url',
        params: {}
    }).then( function(response) {
        console.log(response);
});

Changing the GET method to receive a JSON response is another beast entirely but this works when a service isn't excepting arguments. You would add the arguments in if the opposite were true.

Erik Grosskurth
  • 3,762
  • 5
  • 29
  • 44