【发布时间】:2021-02-02 12:50:34
【问题描述】:
我正在 React 中构建一个 Chrome 扩展程序,该扩展程序连接到后端的 Rails 6 应用程序。我希望 Rails 应用充当 API 并存储来自扩展的数据,但我无法让它接受来自我的扩展的请求。
这是我的扩展中的获取代码:
fetch('https://www.myapp.com/api/post_comment/test', {
method: 'get',
headers: {'Content-Type':'application/json'}
});
这是我在 js 控制台中不断遇到的错误:
从来源访问“https://www.myapp.com/api/test”获取 “http://localhost:3000”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。如果不透明的响应满足您的需求,请设置请求的 模式为“no-cors”以获取禁用 CORS 的资源。
“https://www.myapp.com/api/test”的 FetchEvent 导致网络 错误响应:一个不是响应的对象被传递给 响应()。
我尝试将 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 应用控制器中手动添加标题:
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', 添加到我的获取代码中,我可以发布数据,但我无法检索数据。
【问题讨论】:
标签: ruby-on-rails google-chrome-extension cors fetch-api