我不想通过另一个域登录我的应用程序。我在服务器端设置了 header ,如下所示:
应用程序.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'
}
这些似乎没有任何作用。
在应用程序 Controller 中:
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 请求将起作用并会在屏幕上显示该页面。不过我需要发帖、登录。我做错了什么?
最佳答案
使用 Rack::CORS
gem 。
--
它创建中间件来整理应用程序的所有 header 。我从来没有见过有人在他们的 Controller 中正确地手动实现 header 或其他什么,这个应用程序会为你做到这一点:
#config/application.rb
....
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
关于jquery - CORS post 不适用于 Rails 应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802903/