在百度上搜索“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 theAccess-Control-Allow-Credentialsresponse header. Note: If a wildcard (*) origin is specified, this option cannot be set totrue. Read this security article for more information.
- max_age (number): Sets the
Access-Control-Max-Ageresponse 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.
本文详细介绍了如何在Rails应用中配置rack-cors gem以实现跨域访问,并特别强调了Access-Control-Allow-Credentials的重要性。提供了针对不同Rails版本的具体配置示例。

1万+

被折叠的 条评论
为什么被折叠?



