You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5.1 CORS配置:如何为不同环境设置不同源

如何为Rails 5.1 API的不同环境配置不同的CORS源?

我完全懂你的困扰——固定死的CORS源配置在跨环境部署时太不灵活了,毕竟本地开发、预发布和生产环境的前端域名肯定不一样对吧?下面给你几个实用的解决方案,选最适合你的就行:

方法1:直接通过Rails环境判断(最直观)

在config/initializers/cors.rb里,用Rails.env来区分不同环境的允许源,代码清晰易懂:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    # 根据环境切换允许的源
    case Rails.env
    when 'development'
      origins 'http://localhost:4200'
    when 'production'
      origins 'https://app.mydomain.com'
    # 要是有预发布环境,直接加个分支就行
    when 'staging'
      origins 'https://staging.mydomain.com'
    end

    resource '*', 
      headers: :any, 
      expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], 
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

小提示:你之前代码里的module Api其实没必要保留,除非你的API是作为Rails引擎开发的,普通API应用直接配置即可。

方法2:用环境配置文件集中管理(更优雅)

如果想把CORS源和其他环境配置放在一起,显得更规整,可以在各环境的配置文件里定义:

比如config/environments/development.rb:

Rails.application.configure do
  # 其他开发环境配置...
  config.cors_allowed_origins = ['http://localhost:4200']
end

config/environments/production.rb:

Rails.application.configure do
  # 其他生产环境配置...
  config.cors_allowed_origins = ['https://app.mydomain.com']
end

然后在config/initializers/cors.rb里读取这个全局配置:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins Rails.application.config.cors_allowed_origins
    resource '*', 
      headers: :any, 
      expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], 
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

方法3:用环境变量管理(适合云部署)

如果是用Heroku、AWS这类云平台部署,用环境变量更灵活,不用修改代码就能切换源:

先在本地(可以配合dotenv gem,在.env文件里)或者服务器上设置环境变量:

# 开发环境
CORS_ORIGINS=http://localhost:4200
# 生产环境(支持多个源,用逗号分隔)
CORS_ORIGINS=https://app.mydomain.com,https://another-frontend.example.com

然后在config/initializers/cors.rb里解析这个变量:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    # 把环境变量按逗号分割成数组
    origins ENV['CORS_ORIGINS'].split(',')
    resource '*', 
      headers: :any, 
      expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], 
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

额外注意点

  • 源地址不要加末尾的斜杠(比如你之前写的https://app.mydomain.com/多了个/,可能会导致匹配失败,建议去掉)
  • 配置完后可以用curl -I https://your-api-domain.com/your-test-endpoint查看响应头里的Access-Control-Allow-Origin,确认是否正确生效

内容的提问来源于stack exchange,提问作者rmcsharry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:10:03