2016-08-20 36 views
5

在我的Rails應用程序中,我構建了一項功能,允許用戶使用JavaScript代碼段將應用程序中的數據嵌入到其他網站上。單個Rails路由上的訪問控制 - 允許來源

我的JavaScript代碼段對我的Rails應用程序中返回原始JSON的路線發出GET請求。當代碼片段和JSON共享相同的域時,一切運行良好,但是當我將代碼片段嵌入到另一個站點時,我遇到了CORS問題。

使用解決方案I found here,我已經開始爲CORS配置我的Rails應用程序。

在我application_controller.rb

before_filter :add_allow_credentials_headers 

def add_allow_credentials_headers 
    response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*' 
    response.headers['Access-Control-Allow-Credentials'] = 'true' 
end 

def options 
    head :status => 200, :'Access-Control-Allow-Headers' => 'accept, content-type' 
end 

在我routes.rb

get 'embed_json' => 'application#options', :via => [:options] 

然而,當我打我的瀏覽器上面的路線,應用程序不再返回的JSON對象只是一個空白屏幕。

對於如何最好地處理單個Rails路由上的CORS似乎存在許多衝突的方法。有沒有「Rails方式」來處理這個要求?

回答

2

致電head不會返回JSON by definition。選項散列,當您與head通話時,它將被轉換爲標題。

可能試試這個,options調用會根據需要爲空的響應主體提供標題。對index的調用應該呈現JSON以及您在add_allow_credentials_headers過濾器中設置的標題。

def add_allow_credentials_headers 
    response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*' 
    response.headers['Access-Control-Allow-Credentials'] = 'true' 
    response.headers['Access-Control-Allow-Headers'] = 'accept, content-type' 
end 

def options 
    head :ok 
end 

def index 
    # do something here that renders a JSON response 
end 

而且,在你的Rails應用程序啓用CORS另一個選擇是rack-cors,可能你需要什麼,而不做自己的麻煩。

1

status: :ok添加到您要返回的原始JSON。如果你返回一個空體,添加head :ok返回200個狀態

要只啓用options方法CORS,你可以做的是:

before_filter :add_allow_credentials_headers, only: [:options] 

def add_allow_credentials_headers 
    response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*' # the domain you're making the request from 
    response.headers['Access-Control-Allow-Credentials'] = 'true' 
    response.headers['Access-Control-Allow-Headers'] = 'accept, content-type' 
end 

def options 
    # your json response here or just 'head :ok' if empty 200 response 
end 
1

安裝這種寶石:

gem 'rack-cors', :require => 'rack/cors' 

然後將其添加到您的config/application.rb文件中。

module YourApp 
    class Application < Rails::Application 

    # ... 

    # Rails 3/4 

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

    # Rails 5 

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

    end 
end 

這將做的伎倆閱讀更多。 Cors