Ruby on rails Rails和CORS:如何正确处理初始CORS请求?

Ruby on rails Rails和CORS:如何正确处理初始CORS请求?,ruby-on-rails,cors,Ruby On Rails,Cors,MyEventsController有一个操作,create。这是一个已启用的控制器,因此它在正常的POST请求到达之前接收HTTPOPTIONS请求 当我收到选项请求时,我不想将新事件保存到数据库中,但我能够确保不会发生这种情况的唯一方法是实施感觉像可怕的黑客行为(请参阅下面我的EventsController\create方法)。正确的处理方法是什么 class API::EventsController < ApplicationController skip_before_f

My
EventsController
有一个操作,
create
。这是一个已启用的控制器,因此它在正常的
POST
请求到达之前接收HTTP
OPTIONS
请求

当我收到选项请求时,我不想将新事件保存到数据库中,但我能够确保不会发生这种情况的唯一方法是实施感觉像可怕的黑客行为(请参阅下面我的
EventsController\create
方法)。正确的处理方法是什么

class API::EventsController < ApplicationController

  skip_before_filter :verify_authenticity_token
  before_filter :cors_preflight_check
  after_filter :cors_set_access_control_headers

  # 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'] = 'X-Requested-With, X-Prototype-Version'
      headers['Access-Control-Max-Age'] = '1728000'
      render :text => '', :content_type => 'text/plain'
    end
  end

  # For all responses in this controller, return the CORS access control headers.
  def cors_set_access_control_headers
    headers['Access-Control-Allow-Headers'] = "Content-Type"
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Max-Age'] = "1728000"
  end

  def create
    # Is this a horrible hack?
    if request.method == "OPTIONS"
      render :json => '', :content_type => 'application/json'
      return
    end

    registered_application = RegisteredApplication.find_by(url: request.env['HTTP_ORIGIN'])

    if registered_application.nil?
      render json: "Unregistered application", status: :unprocessable_entity
    else
      event = registered_application.events.new(event_params)

      if event.save
        render json: @event, status: :created
      else
        render @event.errors, status: :unprocessable_entity
      end
    end
  end

private

  def event_params
    params.permit(:name)
  end

end
class API::EventsController'',:content\u type=>'text/plain'
结束
结束
#对于此控制器中的所有响应,返回CORS访问控制标头。
def cors_设置_访问_控制_标题
标题['Access-Control-Allow-headers']=“内容类型”
标题['Access-Control-Allow-Origin']='*'
标题['Access-Control-Allow-Methods']='POST、GET、OPTIONS'
标题['Access-Control-Max-Age']=“1728000”
结束
def创建
#这是一个可怕的黑客吗?
if request.method==“选项”
呈现:json=>'',:content\u type=>'application/json'
返回
结束
registered_application=RegisteredApplication.find_by(url:request.env['HTTP_ORIGIN'])
如果已注册,则为0.nil?
呈现json:“未注册的应用程序”,状态::无法处理的_实体
其他的
event=已注册的应用程序.events.new(事件参数)
如果event.save
呈现json:@事件,状态::已创建
其他的
render@event.errors,状态::无法处理的_实体
结束
结束
结束
私有的
def事件参数
参数许可证(:名称)
结束
结束