Skip to content Skip to sidebar Skip to footer

ContentType: 'application/json' With POST Method (JavaScript)

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: $.

Solution 1:

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.


Solution 2:

Cross domain requests are subject to the same origin policy.

They require permission from the server to:

  • Read the data from the response
  • Make some kind of requests in the first place

You have triggered one the latter conditions, so the browser is making a preflight request using the OPTIONS verb.

The server needs to respond with CORS headers granting permission.

Something like:

Access-Control-Allow-Origin: http://your.server.example.com
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type

… should do the job (untested).

When the browser gets the response, it will then make the POST request.


Post a Comment for "ContentType: 'application/json' With POST Method (JavaScript)"