How to set access-control-allow-origin in webrick under rails?

后端 未结 6 683
广开言路
广开言路 2020-12-02 13:08

I have written a small rails app to serve up content to another site via xmlhttprequests that will be operating from another domain (it will not be possible to get them runn

相关标签:
6条回答
  • 2020-12-02 13:52

    Rails 3.1 - using a controller after_filter did not work for me so I added a custom middleware instead:

    In app/middleware/cors_middleware.rb:

    # For icons to work in Firefox with CDN
    class CorsMiddleware
      def initialize(app)
        @app = app
      end
    
      def call(env)
        status, headers, body = @app.call(env)
        cors_headers = headers.merge({
          'Access-Control-Allow-Origin' => '*',
          'Access-Control-Request-Method' => '*'        
        })
        [status, cors_headers, body]
      end  
    end
    

    In config/application.rb:

    require File.join(Rails.root, "app", "middleware", "cors_middleware")
    config.middleware.insert_before ActionDispatch::Static, CorsMiddleware # Need it early in the chain to work for assets
    
    0 讨论(0)
  • 2020-12-02 13:53

    In case you want the solution as a Rack middleware gem: https://github.com/cyu/rack-cors

    0 讨论(0)
  • 2020-12-02 13:56

    If you're on Rails 2 just add this to your application contoller.

    before_filter :set_access
    
    def set_access
      @response.headers["Access-Control-Allow-Origin"] = "*"
    end
    

    Obviously changing "*" to something a little less open would be a good idea.

    0 讨论(0)
  • 2020-12-02 13:59

    Rails 3.1

    class ApplicationController < ActionController::Base
      protect_from_forgery
      after_filter :set_access_control_headers
    
      def set_access_control_headers
        headers['Access-Control-Allow-Origin'] = '*'
        headers['Access-Control-Request-Method'] = '*'
      end
    end
    
    0 讨论(0)
  • 2020-12-02 14:04

    Rails 2.3.8

    before_filter :allow_cross_domain_access
    def allow_cross_domain_access
      response.headers["Access-Control-Allow-Origin"] = "*"
      response.headers["Access-Control-Allow-Methods"] = "*"
    end
    
    0 讨论(0)
  • 2020-12-02 14:06

    Rails 4 (http://edgeguides.rubyonrails.org/security.html#default-headers)

    In config/application.rb:

    config.action_dispatch.default_headers.merge!({
      'Access-Control-Allow-Origin' => '*',
      'Access-Control-Request-Method' => '*'
    })
    
    0 讨论(0)
提交回复
热议问题