Heroku Rails CORS问题

Lam*_*pbo 3 ruby-on-rails heroku cors angularjs cordova

我已经构建了一个rails restful服务,我在Heroku和一个Angular客户端上托管,我试图从我的本地机器运行.最终,此客户端将被添加到phonegap项目中.但是,现在我正在使用chrome测试应用程序,即我的浏览器一直在返回错误.

XMLHttpRequest cannot load  Origin http://localhost is not allowed by Access-Control-Allow-Origin. 
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息.在推送到Heroku之前我遇到了这个问题,并通过在我的回复中添加访问标题来解决它.

    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'] = 'http://localhost' #*
        headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
        headers['Access-Control-Allow-Headers'] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
        headers['Access-Control-Max-Age'] = "1728000"
end
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用.出于某种原因,这不适用于Heroku.有谁知道如何解决这个问题?

Fea*_*ion 6

Rails 4的一种可能的解决方案(没有检查早期版本).我曾经rails-api创建独立的API服务器.所以,基于的例子ActionController::API.在使用的情况下,相同的解决方案必须正常工作ActionController::Base.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  include ActionController::ImplicitRender
  include ActionController::MimeResponds

  def cors_preflight_check
    headers['Access-Control-Max-Age'] = '1728000'

    render json: {} # Render as you need
  end
end


# config/application.rb
class Application < Rails::Application
  config.action_dispatch.default_headers = {
    'Access-Control-Allow-Origin' => '*',
    'Access-Control-Allow-Methods' => 'POST, PUT, PATCH, DELETE, GET, OPTIONS',
    'Access-Control-Request-Method' => '*',
    'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  }
end


# config/routes.rb
# Last route definition code line
match '*path', to: 'application#cors_preflight_check', via: [:options]
Run Code Online (Sandbox Code Playgroud)

对我来说,这个解决方案似乎不太讨厌.此外,它OPTIONS在"Rails-way"中处理HTTP方法.