ruby-on-rails - Heroku Rails CORS 问题

标签 ruby-on-rails angularjs heroku cordova cors

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

XMLHttpRequest cannot load  Origin http://localhost is not allowed by Access-Control-Allow-Origin. 

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

    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

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

最佳答案

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]

这个解决方案对我来说似乎不那么骇人听闻。此外,它还关注“Rails-way”中的 OPTIONS HTTP 方法。

关于ruby-on-rails - Heroku Rails CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883497/

相关文章:

ruby-on-rails - 我如何优化这个关联链?

javascript - Angular 工厂: Implementing getAll function to consume REST Api

node.js - NodeJS 和 ReactJS 的 Heroku 部署

heroku - Heroku procfile“Procfile中未定义此类进程类型的网络”错误

ruby-on-rails - 处理对 heroku 的 PUT 请求中的 gzipped 正文

ruby-on-rails - 在after_action回调中检测 Action 邮件传递失败

具有图像上传功能的 Javascript(或可能不是)文本编辑器

ruby-on-rails - Rails 创建操作在应该呈现新操作时重定向到索引

angularjs - 如何在 AngularJS 中的两个模块之间共享数据?

angularjs - Angular - 让 ng-bind 处理嵌套指令