Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  39] [ 4]  / answers: 1 / hits: 41578  / 8 Years ago, mon, june 6, 2016, 12:00:00

I've tried both these things separately:



note: url is a variable containing a 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 the system we are posting to requires a header Content-Type with a value application/json.



With the way things are right now, the method used is POST, the Accept header is application/json, and the Content-Type defaults to application/x-www-form-urlencoded; charset=UTF-8



In the first example, if request.setRequestHeader('Content-Type', 'application/json'); is added 1 line above or below the Accept header, the method used 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 it wasn't seen.



In the second example, if contentType: application/json is added anywhere within options, the same thing happens that happened in the first example.



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



Edit: I should add that using the firefox rest client plugin, the json string, url, and accept and content type headers all work fine. We just can't seem to get the content header set on our own page.


More From » jquery

 Answers
85

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




This is because you are making a cross origin request from JS embedded in a webpage. Changing the content-type (to one that you couldn't make with a simple HTML form) triggers a preflight request asking permission from the server to make the actual request.



You need to set up the server to respond with appropriate CORS headers 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 make the POST request you are asking it to make.


[#61884] Friday, June 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
jarod questions
;