2017-04-27 50 views
1

配置/ application.rb中爲什麼不起作用機架?

require_relative 'boot' 
require 'rails/all' 
Bundler.require(*Rails.groups) 

module MyApp 
class Application < Rails::Application 
    config.middleware.insert_before ActionDispatch::Static, Rack::Cors do 
    allow do 
    origins '*' 
    resource '*', :headers => :any, :methods => [:get, :post, :options, :patch, :delete] 
     end 
    end 
    end 
end 

的Gemfile

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

another gems… 

束EXEC耙中間件

use Rack::Cors 

another middleware… 

這是一個錯誤顯示控制檯日誌

XMLHttpRequest cannot load https://example.com. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.

我該怎麼辦?

+0

你使用Rails 5或Rails 4嗎? – akbarbin

+0

@MuhamadAkbarBinWidayat我使用Rails 5! – faara

+0

再次閱讀錯誤消息。 'XMLHttpRequest無法加載https:// example.com'。如果您正在從https:// example.com加載數據,則無論您在本地主機上發送多少個cors頭文件都無關緊要。 ;) – max

回答

-1

試着將你的代碼改成這樣。我試過在我的rails 5中只添加下面的行會工作。然後嘗試重新啓動服務器。

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 
    end 
end 

我希望它的作品。

+0

謝謝你的答案!但是,對不起,錯誤信息沒有改變... – faara

+0

這並不回答這個問題。該錯誤消息清楚地表明,正在向「http:// example.com」(IANA示例域)發出Ajax請求,而不是本地主機。事實上,rails服務器上的CORS頭文件完全不相關。 – max

+0

@faara你能告訴我們ajax如何調用api嗎? – akbarbin