Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest/ajax set Content-Type

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.

like image 288
backcab Avatar asked Jun 06 '16 18:06

backcab


1 Answers

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.

like image 75
Quentin Avatar answered Sep 21 '22 18:09

Quentin