Nat
Nat

Reputation: 3077

JQuery ajax OPTIONS authorisation request not working

I'd like to POST data to another domain and receive the confirmation message returned by the action. So to get CORS to work I've got an options action to handle the OPTION HTTP method (on the same path as the POST) in my rails controller, which currently looks like this:

def options
  headers['Access-Control-Allow-Origin'] = "*"
  headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
  headers['Access-Control-Max-Age'] = '100'
  headers['Access-Control-Allow-Headers'] = '*, x-requested-with, content-type, accept, origin, referer, user-agent'
  render :text => '', :content_type => 'text/plain'
end

My jquery ajax request looks like this: (coffeescript)

$.ajax
  type: 'POST'
  url:  'http://my-other-domain.com/'
  data: data
  contentType: "application/json; charset=UTF-8"
  crossDomain: true
  success: (response) => 
    if response.data_saved
      ...
  error: () => ...

but... it don't work.

The OPTIONS request seems to be working, returning Access-Control-Allow-Origin:* and all, the server receives and processes the POSTed data, but Chrome still throws

XMLHttpRequest cannot load http://my-other-domain.com/. Origin http://my-main-domain.com is not allowed by Access-Control-Allow-Origin.

in the console and fires the error callback.

What am I missing?

Upvotes: 0

Views: 978

Answers (2)

monsur
monsur

Reputation: 47997

The Access-Control-Allow-Origin: * header must be included on all responses, not just on the preflight OPTIONS response. Adding that header on the POST response should fix things.

(Also note that '*' is not a valid value in Access-Control-Allow-Headers, but it shouldn't break anything)

Upvotes: 2

Emre Karataşoğlu
Emre Karataşoğlu

Reputation: 1719

I remember that I had a problem like that , the cross ajax problem , in php I resolved that with header("..."); Then I started to use .getJSON method in Jquery

Upvotes: 0

Related Questions