2015-10-10 33 views
2

我在我的Rails 4应用程序中使用rack-cors gem,以便我可以执行基于JSON的API。我的项目中的所有GET方法工作正常,但POST方法返回500内部服务器错误。POST方法不能在机架轨道上工作4

我做的配置在我application.rb文件是这样的:

module Railsapp 
class Application < Rails::Application  
    config.active_record.raise_in_transactional_callbacks = true 
    config.middleware.insert_before 0, "Rack::Cors" do 
    allow do 
     origins '*' 
     resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete] 
    end 
    end 
end 
end 

application_controller.rb文件看起来像这样:

before_filter :cors_preflight_check 
after_filter :cors_set_access_control_headers headers 

def cors_set_access_control_headers 
headers['Access-Control-Allow-Origin'] = '*' 
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' 
headers['Access-Control-Allow-Headers'] = '*' 
headers['Access-Control-Max-Age'] = "1728000" 
end 

def cors_preflight_check 
if request.method == :options 
    headers['Access-Control-Allow-Origin'] = '*' 
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' 
    headers['Access-Control-Allow-Headers'] = '*' 
    headers['Access-Control-Max-Age'] = '1728000' 
    render :text => '', :content_type => 'text/plain' 
end 
end 

routes.rb文件我已经加入这一行

get '*all' => 'application#cors_preflight_check', :constraints => { :method => 'OPTIONS' } 

我已经尝试了大部分的堆栈溢出解决方案,但它没有帮助。任何人都可以请帮我在这里。

+0

您是否试过rails-api gem? –

回答

0

好了,所以如果你使用的是rack-cors宝石,你不必包括你的application_controllerroutes

的代码在你的application.rb足够的cors_*方法。不过,如果你仍然看到问题,请尝试寻找宝石的rails4应用的示例项目:https://github.com/cyu/rack-cors/blob/master/examples/rails4/

0

https://github.com/cyu/rack-cors/blob/master/lib/rack/cors.rb#L306

架-CORS使用的访问控制允许的凭据'= TRUE,当你不设置虚假选项。

因此,当凭证标志为true时,您不能在'Access-Control-Allow-Origin'中使用通配符。如果你想使用通配符,请这样写。

allow do 
    origins '*' 
    resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false 
end