无法让rails-cors在rails应用程序中工作 [英] Can't get rack-cors working in rails application

查看:123
本文介绍了无法让rails-cors在rails应用程序中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的rails应用程式中导入CORS,因此我为其 rack-cors gem进行了搜寻。我做了一切,在README中说,这是更新Gemfile相应并更新 application.rb 像这样:

I wanted to implement CORS in my rails application, so I googled rack-cors gem for it. And I did everything as was said in README, that is updated Gemfile accordingly and updated application.rb like this:

module YourApp
  class Application < Rails::Application

    # ...

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

  end
end

但它没有工作。不管我做什么,在浏览器控制台中我一直收到消息:

XMLHttpRequest无法加载https://somewebsite.com。

But it didn't work. No matter what I did, in the browser console I kept getting message:
XMLHttpRequest cannot load https://somewebsite.com. Origin http://0.0.0.0:3000 is not allowed by Access-Control-Allow-Origin.

阅读完这篇文章后,原文http://0.0.0.0:3000不被Access-Control-Allow-Origin允许。 博文问题,我意识到,可能在中间件栈中的rack-cors中间件的位置很重要。所以我做的是在github的问题:

After reading this blogpost and issue on github, I realized that maybe position of rack-cors middleware in the middleware stack matters. So I did as was told in the github issue:

module YourApp
  class Application < Rails::Application

    # ...

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

  end
end

之后,当我运行 rake中间件 rack-cors真的在堆栈的顶部。

但它仍然只是不会工作。我不断得到相同的错误。任何人请帮助。

After that, when I run rake middleware rack-cors is really at the top of the stack.
But It still just simply won't work. I keep getting the same error. Anyone, please help.

推荐答案

我遇到了与heroku相同的问题。我发现此博客遇到相同的机架问题。

I ran into the same problem with heroku. I found this blog with the same rack-cors issue.

刚刚将移到使用Rack :: Cors config.ru ,重新部署heroku和它工作。

Just moved the use Rack::Cors to config.ru, redeployed to heroku and it works.

require ::File.expand_path('../config/environment',  __FILE__)
run Rails.application

require 'rack/cors'
use Rack::Cors do

  # allow all origins in development
  allow do
    origins '*'
    resource '*', 
        :headers => :any, 
        :methods => [:get, :post, :delete, :put, :options]
  end
end

这篇关于无法让rails-cors在rails应用程序中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆