JQuery ajax OPTIONS authorisation request not working

為{幸葍}努か 提交于 2019-12-24 20:22:53

问题


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?


回答1:


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)




回答2:


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



来源:https://stackoverflow.com/questions/12621946/jquery-ajax-options-authorisation-request-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!