contentType: 'application / json' with the POST method (JavaScript)

advertisements

I need to create a web server client in JavaScript and I have some problems to define Request headers.

I need POST method and Content-Type: "application/json".

I tried this:

    $.ajax({
            url: 'http://MyWebServiceAddress',
            data: JSON.stringify({user:'user',pass:'pass'}),
            type: 'POST',
            crossDomain: true,
            dataType: 'json',
            success: function () {
                    alert("success")
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Error: " + xhr.status + "\n" +
                        "Message: " + xhr.statusText + "\n" +
                        "Response: " + xhr.responseText + "\n" + thrownError);
            }
        });

But if I put contentType like this:

contentType: 'application/json; charset=utf-8',

and look then the request with Chrome Dev Tools I can see that method was changed to "OPTIONS" and type to "text/plain"

Anyone can help me? I don't have to use Ajax, so if someone know a good JavaScript library to make client easier, maybe can result my problems


You do need to set the contentType header just as you've written; the contentType is for the request itself, while the dataType header is for the response you're expecting back from the server. So if you add that contentType to the $.ajax request, it looks correct.

The "OPTIONS" request is a different issue: that's being sent because you must be making a "cross-origin" request, meaning the ajax request's service address (http://MyWebServiceAddress) is different from the current page's "origin" address. Is that the case? An example would be if your page comes from http://example.com, and you are making a request to http://twitter.com from that page. You can read more about cross-origin, or CORS, requests here. The bottom line is that $.ajax has to make a separate ORIGIN request before posting JSON data like you're doing, and then it will make the POST request -- if and only if the server at http://MyWebServiceAddress is configured to allow CORS requests from your page's domain. See that CORS link above for more details.