2017-04-27 47 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