【发布时间】:2015-12-24 12:13:33
【问题描述】:
我不想通过另一个域登录我的应用程序。我已经在服务器端设置了这样的标题:
应用程序.rb:
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => 'GET,POST,OPTIONS',
'Access-Control-Request-Method' => '*',
'Access-Control-Allow-Headers' => '*',
'Access-Control-Max-Age' => '1728000'
}
这些似乎没有任何作用。
在应用程序控制器中:
before_filter :expire_hsts
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
#protect_from_forgery with: :exception
protect_from_forgery
before_filter :current_user, :cors_preflight_check
after_filter :cors_set_access_control_headers
# For all responses in this controller, return the CORS access control
headers.
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = "1728000"
end
# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.
def cors_preflight_check
if request.method == :options
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '*'
render :text => '', :content_type => 'text/plain'
end
end
这是我用 jquery 发送的请求:
$.ajax({
url: "http://localhost:3000/login",
type: "POST",
crossDomain: true,
data: {
"email": "admin@example.com",
"password" : "foobar",
"remember_me": "0"
}
/*xhrFields: {
withCredentials: true
}*/
}).done(function(result) {
$('html').html(result);
});
对该页面的 GET 请求将起作用,并将在屏幕上显示该页面。不过,我需要发布,才能登录。我做错了什么?
【问题讨论】:
标签: jquery ruby-on-rails ajax cors remote-access