pruett
pruett

Reputation: 2121

$.ajax 400 Bad Request

The goal is to send an object via ajax to another server, which I've set up for CORS, here's the $.ajax snippet:

$.ajax "#{config.url_root}/register",
  type: "POST"
  data: model.attributes
  dataType: "json"
  success: (data, text, xhr) -> console.log data, text, xhr
  error: (xhr, text, error) -> console.log text, error

correctly POSTS the data, but with a contentType of application/x-www-urlencoded; charset utf-8; When I explicity set the value of contentType to "application/json; charset=utf-8", it executes with a request method ofOPTIONS?! and fails to deliver the data (404 Not Found`)

Upvotes: 0

Views: 1902

Answers (1)

idbehold
idbehold

Reputation: 17168

By setting the XMLHttpRequest's Content-Type to application/json you're turning a simple cross-domain request into a non-simple cross-domain request (read more about CORS here) which means that your browser must send an preflight (OPTIONS) request prior to your intended request. This is done to verify with the server that the client from a different origin is allowed to make said request.

The only "simple" headers you can set are: Accept, Accept-Language, Content-Language, Last-Event-ID, and Content-Type (if it is set to one of: application/x-www-form-urlencoded, multipart/form-data, or text/plain).

Upvotes: 1

Related Questions