Ruby on rails 如何在Rails中配置CORS接受头

Ruby on rails 如何在Rails中配置CORS接受头,ruby-on-rails,ruby-on-rails-3,cors,Ruby On Rails,Ruby On Rails 3,Cors,我正在尝试在rails中配置CORS accept头文件,当我按照下面的方法进行配置时,它似乎不允许我这样做,因为它会在选项请求中抛出404 应用程序控制器 class ApplicationController < ActionController::Base before_action :set_paper_trail_whodunnit, :cors_set_access_control_headers skip_before_filter :verify_authentic

我正在尝试在rails中配置CORS accept头文件,当我按照下面的方法进行配置时,它似乎不允许我这样做,因为它会在选项请求中抛出404

应用程序控制器

class ApplicationController < ActionController::Base
  before_action :set_paper_trail_whodunnit, :cors_set_access_control_headers
  skip_before_filter :verify_authenticity_token

  def verify_api_key
    return if request.headers["HTTP_API_KEY"] == Rails.configuration.x.api_key
    render json: { status: :unauthorized }, status: :unauthorized
  end
def cors_preflight_check
  if request.method == 'OPTIONS'
    cors_set_access_control_headers
    render text: '', content_type: 'text/plain'
  end
end

protected

def cors_set_access_control_headers
  response.headers['Access-Control-Allow-Origin'] = '*'
  response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS'
  response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token, Auth-Token, Email, X-User-Token, X-User-Email'
  response.headers['Access-Control-Max-Age'] = '1728000'
end
end


有人能帮忙吗?

如果您不介意使用gems,请查看

config/application.rb
中,您可以配置所有需要的内容

module YourApp
  class Application < Rails::Application
    # ...

    # Rails 5

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options]
      end
    end

    # Rails 3/4

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options]
      end
    end
  end
end
moduleyourapp
类应用程序
您是否尝试过从
CORS.rb
配置CORS?它位于初始值设定项目录下
module YourApp
  class Application < Rails::Application
    # ...

    # Rails 5

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options]
      end
    end

    # Rails 3/4

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options]
      end
    end
  end
end