jQuery ajax OPTIONS授权请求不起作用
我想将数据发布到另一个域,并接收操作返回的确认消息.因此,为了使CORS正常工作,我在rails控制器中有一个options动作来处理OPTION HTTP方法(与POST处于同一路径),
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
我的jquery ajax请求看起来像这样:(咖啡脚本)
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.
OPTIONS请求似乎正在工作,返回Access-Control-Allow-Origin:*
,所有,服务器接收并处理了POSTed数据,但Chrome仍然抛出
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.
我想念什么?
Access-Control-Allow-Origin: *
标头必须包含在所有响应中,而不仅仅是预检OPTIONS响应中.在POST响应上添加该标头应该可以解决问题.
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.
(还请注意,'*'在Access-Control-Allow-Headers
中不是有效值,但不应破坏任何内容)
(Also note that '*' is not a valid value in Access-Control-Allow-Headers
, but it shouldn't break anything)