CORS 帖子不适用于 rails 应用程序
Posted
技术标签:
【中文标题】CORS 帖子不适用于 rails 应用程序【英文标题】:CORS post doesn't work with rails app 【发布时间】: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 请求将起作用,并将在屏幕上显示该页面。不过,我需要发布,才能登录。我做错了什么?
【问题讨论】:
【参考方案1】:使用Rack::CORS
gem。
--
它会创建中间件,为您的应用整理出所有的标头。我从未见过有人在他们的控制器或其他任何东西中手动正确地实现标头,这个应用程序会为您完成:
#config/application.rb
....
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
【讨论】:
如果您需要,我可以解释更多。不过,安装和运行这个 gem 应该是不言自明的。以上是关于CORS 帖子不适用于 rails 应用程序的主要内容,如果未能解决你的问题,请参考以下文章
创建反应应用程序:setupProxy 不断返回被 CORS 策略阻止的 401,不适用于远程 URL?