ruby-on-rails - 如何在 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
?我会很感激能得到任何人的帮助。先感谢您。
解决方案
如果您使用的是 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 '*'
然后相应地设置它。
这对我有用。希望它也适用于你。干杯
推荐阅读
- android - 为什么我无法创建要求 2 个文本的自定义意图?
- asp.net-core - 无法将 ASP.NET 核心应用程序作为 Windows 服务运行
- c# - 调用 Task.WhenAll 后在 C# 中捕获 AggregateException
- javascript - 访问 json 对象给出未定义的
- kotlin - 在 kotlin 中使用具有泛型类型的类型别名?
- mysql - 如何通过加入获得分组结果
- python - Opencv DNN 网络 1x1 的大小
- laravel - 弃用通知和错误:依赖项安装失败
- node.js - 有没有办法将元数据写入 Node.js 中的 docx 文件?
- javascript - 请启用 JavaScript 以继续使用此应用程序。- ng服务