【发布时间】:2013-07-25 08:31:56
【问题描述】:
如何禁用 cors?出于某种原因,我通配了允许的来源和标头,但我的 ajax 请求仍然抱怨我的 CORS 策略不允许来源....
我的应用程序控制器:
class ApplicationController < ActionController::Base
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-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-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
private
# get the user currently logged in
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
路线:
match "*all" => "application#cors_preflight_check", :constraints => { :method => "OPTIONS" }
match "/alert" => "alerts#create"
match "/alerts" => "alerts#get"
match "/login" => "sessions#create"
match "/logout" => "sessions#destroy"
match "/register" => "users#create"
编辑---
我也试过了:
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options]
end
end
在 application.rb 中
--编辑 2---
我认为问题在于 Chrome 扩展程序可能不支持 CORS。如何绕过 CORS 获取信息?我应该如何应对预检检查?
【问题讨论】:
-
不是“禁用 CORS”但实际上没有策略?我似乎无法回应任何请求。
-
你在 localhost 上使用这个吗?
标签: ruby-on-rails cors