Rails 5.1 CORS-如何为不同的环境设置不同的来源 [英] Rails 5.1 CORS - how to set different origins for different environments

查看:107
本文介绍了Rails 5.1 CORS-如何为不同的环境设置不同的来源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Rail 5.1 API的rack-cors gem.

I am using the rack-cors gem with a Rail 5.1 API.

根据文档,我具有以下初始化程序:

I have the following initializer as per the documentation:

config/initializers/cors.rb

config/initializers/cors.rb

module Api
  Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins ['http://localhost:4200','https://app.mydomain.com/']

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

但是,这意味着当部署到生产环境中时,我的api将接受来自任何localhost:4200来源的请求.

However, this means that when deployed to production my api will accept requests from any localhost:4200 origin.

如何区分这些设置,以便不同的环境可以具有不同的允许来源?

How can I separate these settings out so that different environments can have different allowed origins?

推荐答案

有几种不同的选择.一种是使用secrets.yml文件.在那里,您可以为每个环境定义不同的值,例如:

There are a few different options. One is to use secrets.yml file. There you can define different values per environment, let's say:

development:
  allowed_origins:
    - http://localhost:4200

production:
  allowed_origins:
    - http://productionurl1.com
    - http://productionurl2.com

然后可以在您的配置文件中

Then in your configuration file you can do

module Api
  Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins Rails.application.secrets.allowed_origins
    end
  end
end

另一个选项(摘自注释)是使用环境文件,例如:

Another option (taken from the comments) is to use the environment files, eg:

development.rb

development.rb

config.allowed_cors_origins = ["http://localhost:4200"]

然后在cors.rb初始化程序中,您可以执行以下操作:

Then in the cors.rb initializer you can do:

Rails.application.config.allowed_cors_origins 

(因为将在环境配置文件之后调用初始化程序,所以应该可以使用).

(since initializer will be called after the environment config file, this should work).

这篇关于Rails 5.1 CORS-如何为不同的环境设置不同的来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆