【问题标题】:For CORS Error Do i need to configure on client side(Angular js) also?对于 CORS 错误,我还需要在客户端(Angular js)进行配置吗?
【发布时间】:2016-02-14 20:10:28
【问题描述】:

错误:XMLHttpRequest 无法加载 https://thirdPartyasite/template.html。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://localhost:3000'。

我正在使用 Rails 应用程序,该应用程序通过 ajax 调用使用跨组织数据。此问题提供的答案不起作用。

1)How to set access-control-allow-origin in webrick under rails?

2)https://demisx.github.io/rails-api/2014/02/18/configure-accept-headers-cors.html

3)Allow anything through CORS Policy.

我无法控制客户端应用程序。如何克服这个问题。

我试过这个:

before_filter :set_headers
  def set_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

还是会出现同样的错误。

也试过这个: 在 gem 文件中添加:gem 'rack-cors', :require => 'rack/cors' 在 config/application.rb 中:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

仍然遇到同样的错误。

为开发环境工作: 安装 CORS Chrome 插件。 但我需要适当的解决方案

【问题讨论】:

  • 您可能需要发布一些代码(到目前为止您所做的一切都不起作用)。
  • @LeonelMachavaI 用我的尝试更新了我的问题

标签: javascript ruby-on-rails angularjs ajax cors


【解决方案1】:

CORS 仅是服务器端约束。

如果您可以访问您的 Rails 应用程序,最好使用 Rack-CORS gem 来启用特定资源/来源:

#config/application.rb
...
  config.middleware.insert_before 0, "Rack::Cors" do
    allow do
      origins '*'
      resource '*', :headers => :any, :methods => [:get, :post, :options]
    end
  end

如果您有权访问您的服务器端 Rails 应用程序,则需要获得访问权限,否则它将无法工作。

【讨论】:

    【解决方案2】:

    当您使用 CORS 采购 Angular 模板时,Angular $sceDelegateProvider 可能会引发异常。更多信息请阅读sceDelegateProvider official documentation

    出于测试目的,您可以使用:

    angular.module('myApp', []).config(function($sceDelegateProvider) {
      $sceDelegateProvider.resourceUrlWhitelist([
            'self',
            'http://**',
            'https://**'
      ]);
    });
    

    【讨论】:

    • 这可能是我只要求角模板的问题。但我无权访问我让人们知道的那个代码,我会尝试
    • 我有机会浏览代码他们只配置了一定数量的白名单网址。谢谢您的建议。
    【解决方案3】:

    您不需要在 Angular 上进行任何配置。

    要启用 CORS,您只需配置服务器,如您在发布的答案的链接中所见。

    【讨论】:

    • 我尝试了每件事,但仍然抛出错误但标题已添加到响应中。
    猜你喜欢
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2021-07-26
    • 2021-01-04
    • 1970-01-01
    • 2011-03-23
    • 2018-08-11
    相关资源
    最近更新 更多