【问题标题】:Enable CORS in Grape on Rails在 Grape on Rails 中启用 CORS
【发布时间】:2016-09-13 19:20:40
【问题描述】:

我正在使用 Grape on Rails。虽然我无法为它设置 CORS。

rack-cors gem 解释了如何在 application.rb 中为“Rails”设置它。虽然没有展示如何为 Grape on Rails 启用它。

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails cors grape-api


    【解决方案1】:

    设置 Rack-CORS

    几个简单的步骤,我们就可以开始了!

    将以下内容添加到您的 Gemfile 和捆绑安装中:

    gem 'rack-cors', :require => 'rack/cors'
    

    将您的 API 模块添加到 config/application.rb 并配置您的 Rack-CORS 中间件:

    module MyAppRails  
      class Application < Rails::Application
        config.middleware.use Rack::Cors do
          allow do
            origins "*"
            resource "*", headers: :any, methods: [:get, :post, :put, :delete, :options]
          end
        end
        config.active_record.raise_in_transactional_callbacks = true
      end
    

    使用origins "*",我们指定我们的 API 将接受来自整个互联网中任何域的 HTTP 请求。

    通过resource "*",我们指定跨域请求可以访问我们的任何资源(尽管我们目前只有一个资源——毕业生资源)。

    然后我们指定将接受使用任何 HTTP 方法的跨域请求——尽管,如果您还记得,我们在 API 模块中定义了毕业生类,以仅响应所有毕业生或仅一名毕业生的请求。我们可以稍后添加其他 HTTP 方法。

    【讨论】:

      【解决方案2】:

      您可以按照葡萄问题之一中的建议手动添加标题:https://github.com/ruby-grape/grape/issues/170

      我会尝试使用 rack-cors 中间件:要么直接使用它,要么用 Grape 中间件包装它 (http://www.rubydoc.info/github/intridea/grape/Grape/Middleware/Base)

      【讨论】:

        猜你喜欢
        • 2019-01-19
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 2015-02-19
        • 1970-01-01
        • 2015-11-02
        • 1970-01-01
        相关资源
        最近更新 更多