How can I fix the 'CORS policy' error I'm getting while trying to run my React-admin app on Rails 6 and ActiveStorage?

huangapple go评论76阅读模式
英文:

How can I fix the 'CORS policy' error I'm getting while trying to run my React-admin app on Rails 6 and ActiveStorage?

问题

I am using Rails 6 和 ActiveStorage to store files on S3. 我在尝试运行我的 react-admin 应用时遇到了一个 CORS 错误。我的 react-admin 前端显示的错误信息如下:

从来源 'http://my-react-admin-app.com' 尝试访问 'https://my-backend.com' 的请求已被 CORS 策略阻止:预检请求的响应未通过访问控制检查:所请求的资源上没有 'Access-Control-Allow-Origin' 标头。如果不透明的响应符合您的需求,请将请求的模式设置为 'no-cors',以在禁用 CORS 的情况下获取资源。
fetch.js:50 GET https://my-backend.com/data?_end=100&_order=ASC&_sort=id&_start=0&locale=en net::ERR_FAILED.

我已经为我的存储桶设置了以下 CORS 策略(但仍然不起作用):

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET",
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "X-Total-Count"
        ]
    }
]

有什么指导意见吗?请注意:当我在本地运行一切时,一切都按预期工作。

我的 Gemfile 包含:

gem "rails", "~> 6.0.0"
gem "aws-sdk-s3", require: false
gem "rack-cors", "~> 1.0.3"

我的 cors.rb 文件内容如下:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "*"
    resource "*", 
      headers: :any, 
      methods: [:get, :post, :put, :delete, :options],
      expose: "X-Total-Count"
  end
end
英文:

Im making use of Rails 6 and ActiveStorage to store files on S3.

I get a CORS error when I try to run my react-admin app.

Error message from my react-admin front end:

Access to fetch at 'https://my-backend.com' from origin 'http://my-react-admin-app.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
fetch.js:50     GET https://my-backend.com/data?_end=100&_order=ASC&_sort=id&_start=0&locale=en net::ERR_FAILED.

I have set up CORS policy for my bucket as follows (and it still wont work):

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET",
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "X-Total-Count"
        ]
    }
]

Any pointers? - NOTE: everything works as it should when I run everything locally.

My gemfile has:

gem "rails", "~> 6.0.0"
gem "aws-sdk-s3", require: false
gem "rack-cors", "~> 1.0.3"

My cors.rb:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "*"
    resource "*",
      headers: :any,
      methods: [:get, :post, :put, :delete, :options],
      expose: "X-Total-Count"
  end
end

答案1

得分: 1

错误看起来是由于服务器(Rails后端)上的CORS设置引起的,而不是S3。这可能是因为Rails后端没有提供请求资源中应该存在的'Access-Control-Allow-Origin'标头。

解决此问题需要遵循多个步骤。确保在进行以下每个更改后重新启动Rails服务器。

  1. 确保Rails服务器配置中的CORS设置正确(config/application.rb文件或config/initializers/cors.rb)。你的cors.rb看起来没问题,但请检查它是否位于config/initializers路径下,并且Rails应用程序是否正确地引用它。

如果错误仍然存在,然后:

  1. 尝试在config/application.rb中添加以下设置:(注意:用实际的前端域名替换http://react-app.com。)
module YourAppName
  class Application < Rails::Application
    # To initialize configuration defaults for originally generated Rails version
    config.load_defaults 6.0

    # Rest of the code

    # To configure CORS
    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'http://react-app.com'
        resource '*', 
          headers: :any, 
          methods: [:get, :post, :put, :patch, :delete, :options, :head],
          expose: ['X-Total-Count']
      end
    end
  end
end

如果错误仍然存在,然后:

  1. 检查是否有代理或其他可以覆盖CORS设置的服务器设置。检查Nginx或Apache之类的Web服务器是否没有剥离CORS标头。

如果错误仍然存在,然后:

  1. 确保在Rails配置的config.hosts列表中列出了React应用程序的域名(特别是如果你使用的是Rails 6)。

如果错误仍然存在,然后:

  1. 如果你的API在不同路径下提供服务,请将该路径添加到resources语句中,如resource 'api/*'

希望这能解决你的问题。

英文:

As I can see the error is due to CORS settings on the server (Rails backend) not with S3. This can be because 'Access-Control-Allow-Origin' header is not present in the request resource that should be provided by Rails backend.

There are multiple steps you have to follow to solve this issue. Make sure to restart Rails server after making each of the following changes.

  1. Ensure that CORS settings are correct in Rails server configuration (config/application.rb file or config/initializers/cors.rb). Your cors.rb looks fine but check whether it is located in config/initializers path and Rails application is picking it up correctly.

If error still persist, then:

  1. Try adding the following settings to config/application.rb as follows: (Note: Replace http://react-app.com with actual frontend domain name.)

    module YourAppName
    class Application < Rails::Application
    # To initialize configuration defaults for originally generated Rails version
    config.load_defaults 6.0

     # Rest of the code
    
     # To configure CORS
     config.middleware.insert_before 0, Rack::Cors do
       allow do
         origins &#39;http://react-app.com&#39;
         resource &#39;*&#39;,
           headers: :any,
           methods: [:get, :post, :put, :patch, :delete, :options, :head],
           expose: [&#39;X-Total-Count&#39;]
       end
     end
    

    end
    end


If error still persist, then:

  1. Check for any proxies or any other server settings that can override your CORS settings. Check whether web server like Nginx or Apache is not stripping out CORS headers.

If error still persist, then:

  1. Make sure domain of React App is listed in the config.hosts list in Rails configuration (especially if you are using Rails 6).

If error still persist, then:

  1. If you are serving your aPI under a different path, then add the path to the resources statement as resource &#39;api/*

Hope this will solve your issue.

huangapple
  • 本文由 发表于 2023年5月20日 21:32:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定