XMLHttpRequest / ajax set Content-Type

I tried both of these things separately:

note: url is a variable containing https url, and jsonString contains a valid json string

var request = new XMLHttpRequest(); try{ request.open("POST", url); request.setRequestHeader('Accept', 'application/json'); request.send(jsonString); } catch(e) { alert(e); } 

and

 var options = { type: "POST", url: url, dataType: "json", data: jsonString, accept: "application/json" }; $.ajax(options) 

The problem is that the system we are sending requires a Content-Type header with a value of "application / json".

Currently, the POST method is used, the Accept header is "application / json" and the default Content-Type is "application / x-www-form-urlencoded; charset = UTF-8"

In the first example, if request.setRequestHeader ('Content-Type', 'application / json'); 1 line is added above or below the Accept header, the method uses the changes to OPTIONS, the Accept header changes to "text / html, application / xhtml + xml, application / xml; q = 0.9, /; q = 0.8" and the Content-Type header disappears as if they had not seen him.

In the second example, if contentType: "application / json" is added anywhere in the parameters, the same thing happens as in the first example.

What is the correct way to set the Content-Type header in ajax or XMLHttpRequest?

Edit: I have to add that with the firefox rest client plugin, the json string, url, accept and content type strings all work fine. We simply cannot force the content header to be set on our own page.

+6
source share
1 answer

In the first example, if request.setRequestHeader ('Content-Type', 'application / json'); 1 line is added above or below the Accept header, the method used is changed to OPTIONS

This is because you are making a cross-search request from JS embedded in a web page. Changing the content-type (to the one that you could not do using a simple HTML form) launches a pre-sale request with a request for permission from the server to make the actual request.

You need to configure the server to respond with the appropriate CORS headers in order to grant permission.

 HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Access-Control-Allow-Origin: http://your.site.example.com Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: Content-Type 

Then the browser will execute the POST request that you ask to do.

+6
source

All Articles