我正在 React 中构建一个 Chrome 扩展,它连接到后端的 Rails 6 应用程序。我希望 Rails 应用程序充当 API 并存储来自扩展程序的数据,但我无法让它接受来自我的扩展程序的请求。
这是我的扩展程序中的提取代码:
fetch('https://www.myapp.com/api/post_comment/test', {
method: 'get',
headers: {'Content-Type':'application/json'}
});
这是我在 js 控制台中不断出现的错误:Access to fetch at 'https://www.myapp.com/api/test' from origin 'http://localhost:3000' 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.
The FetchEvent for "https://www.myapp.com/api/test" resulted in a network error response: an object that was not a Response was passed to respondWith().
我尝试将 rack-cors gem 添加到我的 Rails 应用程序中:
#Gemfile:
gem 'rack-cors'
#config/initializers/cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/api/*', headers: :any, methods: [:get, :post, :patch, :put]
end
end
我还尝试在我的 Rails 应用程序 Controller 中手动添加标题:before_action :cors_preflight_check
after_action :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end
# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.
def cors_preflight_check
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
render :text => '', :content_type => 'text/plain'
end
但我仍然收到错误。有谁知道我该如何解决这个问题?如果我添加
mode: 'no-cors',
对于我的提取代码,我可以发布数据,但无法检索数据。
最佳答案
从 config/cors.rb
移动您的配置至 config/initializers/cors.rb
config/initializers/
中的所有文件将在 rails 启动时加载。
也有可能被 rails 6 新功能阻止以阻止不需要的主机。
将以下代码段添加到 config/application.rb
或 env 特定文件 config/environments/
config.hosts.clear
检查 Upgraded Rails to 6, getting Blocked host Error
关于ruby-on-rails - 无法从获取请求中获取 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64432515/