【问题标题】:Can't get 'Access-Control-Allow-Origin' header from fetch request无法从获取请求中获取“Access-Control-Allow-Origin”标头
【发布时间】: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


    【解决方案1】:

    将您的配置从 config/cors.rb 移动到 config/initializers/cors.rb

    config/initializers/ 中的所有文件都将在 rails 启动时加载。

    也可以通过 rails 6 新功能阻止不需要的主机。

    将以下 sn-p 添加到 config/application.rbconfig/environments/ 中的特定环境文件

      config.hosts.clear
    

    查看Upgraded Rails to 6, getting Blocked host Error

    【讨论】:

    • 很好,但我移动了文件,但仍然出现错误。
    • 删除这个 cors_set_access_control_headers 和 cors_preflight_check。不需要
    • 这实际上是问题所在 - 我注意到我实际上被重定向到一个错误页面,该页面没有包含在 cors.rb 文件中,这就是我仍然收到消息的原因。一个我停止重定向到错误页面,它终于开始工作了。
    【解决方案2】:

    在扩展中,您有两个来源 - 内容脚本注入的页面来源和后台脚本来源。

    为了让后台脚本能够连接到您的 api - 您需要将 "https://www.myapp.com/" 添加到清单的 permissions,它不受常规 CORS 检查的约束。内容脚本可以通过message passing与后台对话,从而可以避免CORS:

    // from content script:
    chrome.runtime.sendMessage({action: "doSomeAction"}, function(response) {
      console.log(response);
    });
    
    //in background script:
    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
        if (request.action == "doSomeAction") {
          fetch('https://www.myapp.com/api/post_comment/test', {
            method: 'get',
            headers: {'Content-Type':'application/json'}
          }).then(function(response){
            // do something with response and pass pack to content script:
            sendResponse({foo: "bar"});
          });
          return true; // keep message channel so sendResponse is available in 
        }
      });
    

    至于 rails CORS - 我首先要确保标题存在:

    curl -IX OPTIONS https://www.myapp.com/api/post_comment/test -H 'Access-Control-Request-Method: GET' -H 'Origin: http://someorigin.example.com'
    

    这应该返回类似:

    HTTP/2 200
    server: nginx
    date: Thu, 22 Oct 2020 19:50:00 GMT
    access-control-allow-origin: http://someorigin.example.com
    access-control-allow-methods: GET, POST, OPTIONS
    access-control-expose-headers:
    access-control-max-age: 7200
    cache-control: no-cache
    x-request-id: 5846b7400a15b19398c96bec7faac570
    x-runtime: 0.001532
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-13
      • 2016-08-03
      • 2015-12-03
      • 2022-09-27
      • 1970-01-01
      • 2015-05-30
      • 2015-11-09
      • 2017-10-05
      相关资源
      最近更新 更多