已经在Rails中设置了Access-Control-Allow-Origin,仍然抱怨“请求的资源上没有'Access'Control-Allow-Origin'标头”

时间:2017-05-09 11:49:53

标签: ruby-on-rails cors

在Ruby on Rails API中遇到CORS问题:我已经在我的config / application.rb中将Access-Control-Allow-Origin设置为“*”,如下面的代码所示。但是,当我的前端向后端API发出GET或POST请求时,我收到错误“No'Access-Control-Allow-Origin'标头出现在请求的资源上。因此不允许原点'http://localhost:8888'访问“。

require_relative 'boot'

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module MyapplicationApi
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    # config.load_defaults 5.1

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true
    config.action_dispatch.default_headers = {
      'Access-Control-Allow-Origin' => '*',
      'Access-Control-Request-Method' => %w{GET POST PUT OPTIONS}.join(",")
    }
  end
end

我也试过添加以下几行无效:

'Access-Control-Request-Method' => '*',
'Access-Control-Allow-Methods' => 'POST, PUT, DELETE, GET, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你使用过

吗?
gem 'rack-cors'
Gemfile中的

如果没有尝试添加此项。这将有所帮助