rails跨域访问配置

本文详细介绍了如何在Rails应用中配置rack-cors gem以实现跨域访问,并特别强调了Access-Control-Allow-Credentials的重要性。提供了针对不同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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值