2017-04-15 51 views
2

我在Rails5上,我想讓我的一條路線上的CORS。以下是我如何允許CORS用於我的所有路線,但有沒有辦法只爲一個端點添加白名單?如何爲選定的路線導軌啓用CORS

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

回答

2

要允許跨域請求僅特定端點的路徑,把它作爲第一resource ARG:

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

這將允許跨域請求只爲路徑/endpoint/to/allow

如果你想允許多個路徑,你可以指定多個resource聲明:

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

https://github.com/cyu/rack-cors#resource有更多的細節。