rails跨域訪問配置

    在百度上搜索“rails跨域訪問”會出現很多關於跨域訪問的文章,其實大都是摘自Git上rack-cors的readme:

    https://github.com/cyu/rack-cors/blob/master/README.md

    但是大多摘抄都少了對Access-Control-Allow-Credentials這個頭參數的設置,這也就是我踩得坑,所以文檔一般還是要看官方的。

    一般rails跨域訪問設置如下:

1.安裝gem包:

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

2.修改application.rb代碼:

module YourApp
  class Application < Rails::Application

    # ...
    
    # Rails 5

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

    # Rails 3/4

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
    
  end
end

3.重啓OK。

    可是如果前端應用不接受Access-Control-Allow-Origin: 參數爲 *,必須指定域名,那你代碼就要寫成下面這樣:

module YourApp
  class Application < Rails::Application

    # ...
    
    # Rails 5

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'http://127.0.0.1:8000' # 可以接受字符串數組或者是正則表達式
        resource '*', :headers => :any, :methods => [:get, :post, :options],:credentials =>true
      end
    end

    # Rails 3/4

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins 'http://127.0.0.1:8000' # 可以接受字符串數組或者是正則表達式
        resource '*', :headers => :any, :methods => [:get, :post, :options],:credentials =>true
      end
    end
    
  end
end

原因是:

A Resource path can be specified as exact string match (/path/to/file.txt) or with a '*' wildcard (/all/files/in/*). To include all of a directory's files and the files in its subdirectories, use this form: /assets/**/*. A resource can take the following options:

  • methods (string or array or :any): The HTTP methods allowed for the resource.
  • headers (string or array or :any): The HTTP headers that will be allowed in the CORS resource request. Use :anyto allow for any headers in the actual request.
  • expose (string or array): The HTTP headers in the resource response can be exposed to the client.
  • credentials (boolean, default: false): Sets the Access-Control-Allow-Credentials response header. Note: If a wildcard (*) origin is specified, this option cannot be set to true. Read this security article for more information.
  • max_age (number): Sets the Access-Control-Max-Age response header.
  • if (Proc): If the result of the proc is true, will process the request as a valid CORS request.
  • vary (string or array): A list of HTTP headers to add to the 'Vary' header.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章