简体   繁体   中英

Force AngularJS $http.post to return JSON

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM