【问题标题】:How to add response header in VHost or Passeneger (Ruby)如何在 VHost 或 Passeneger (Ruby) 中添加响应标头
【发布时间】:2012-08-25 00:48:20
【问题描述】:

我对同源策略有疑问。我想提出跨域请求 - 我找到了很好的解决方案:http://www.w3.org/TR/cors/

但我不想在 Apache 中设置标头,因为我有很多域并且只有一个需要它。是否可以通过虚拟主机或乘客添加 Access-Control-Allow-Origin 标头?

我这样做,因为我需要在 Chrome/Mozilla 插件中使用 Redmine REST API (XHR)。

【问题讨论】:

    标签: passenger redmine virtualhost cors


    【解决方案1】:

    我也有类似的要求。如果您希望 Redmine 提供这些标头,那么您需要修改 Redmine 源。我写了a blog post about doing this

    感谢this blog post 了解大部分细节。

    为方便起见,我将在这里重现我必须做的事情:


    首先让我们解决预检检查。为此,我在/app/controllers/cors_controller.rb 添加了一个全新的控制器。它看起来像:

    class CorsController < ApplicationController
    
        skip_before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
    
        def preflight
                headers['Access-Control-Allow-Origin'] = '*'
                headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
                headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Content-Type'
                headers['Access-Control-Max-Age'] = '1728000'
                render :text => '', :content_type => 'text/plain'
        end
    
    end
    

    很简单的东西。然后我将所有OPTIONS 请求路由到/config/routes.rb 中的这个控制器:

    match '*path', :to => 'cors#preflight', :constraints => {:method => 'OPTIONS'}
    

    已完成预检检查,这只是按照 Tom 的建议,在 /app/controllers/application_controller.rb 中使用 after_filter 将标头添加到主响应的情况:

    class ApplicationController < ActionController::Base
      include Redmine::I18n
      # ...
      before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
    
      #************ Begin Added Code ****************
      after_filter :cors_set_access_control_headers
    
      # For all responses in this application, return the CORS access control headers.
    
      def cors_set_access_control_headers
        headers['Access-Control-Allow-Origin'] = '*'
        headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
        headers['Access-Control-Max-Age'] = "1728000"
      end
      #************* End Added Code *****************
      #...
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2015-09-11
      • 2021-09-30
      • 2021-02-17
      • 1970-01-01
      相关资源
      最近更新 更多