首页 > 解决方案 > 如何在 Heroku 上部署的 Ruby on Rails 6 API 后端中允许 CORS

问题描述

我知道似乎有一些与该主题相关的答案,但到目前为止,没有一个对我有用。我用 React 构建了一个带有前端的 Rails API 后端。该应用程序运行良好,但在我添加了一些功能并再次部署后,我的 CORS 开始出现问题。我添加的功能与 Redis 和 Action 电缆有关。现在我收到了这个错误:Access to XMLHttpRequest at 'https://myestateapi.herokuapp.com/top_apartment' from origin 'https://frozen-bastion-98066.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.我的设置没有改变我不知道为什么我会得到这个。在我的config/application.rb我有这个

   Rails.application.config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
      allow do
        origins '*'

        resource '*',
                 headers: :any,
                 methods: %i[get post put patch delete options head]
      end
    end

这段代码运行良好。什么可能导致此错误?或者任何人都可以提出比 更好的宝石rack-cors?我会很感激能得到任何人的帮助。先感谢您。

标签: ruby-on-railsruby

解决方案


如果您使用的是 Rails 6:

首先转到您的Gemfile并取消注释gem 'rack-cors'。然后运行bundle install

之后转到config/initializers文件夹。在那里,您应该找到一个名为cors.rb.

取消注释看起来像这样的代码

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'example.com'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

更改说明或如果您的请求将来自特定来源的行origins 'example.com'origin '*'然后相应地设置它。

这对我有用。希望它也适用于你。干杯


推荐阅读