0

Having trouble with CORS in Ruby on Rails API: I have already set the Access-Control-Allow-Origin as "*" in my config/application.rb, as shown in the code below. However, when my frontend is making GET or POST requests to the backend API I get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access."

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

I have also tried adding the following lines to no avail:

'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'

Thanks for any help!

Music Map
  • 75
  • 7

1 Answers1

1

Have you used

gem 'rack-cors'

in Gemfile

If not try to add this. It will helps

shivashankar
  • 1,147
  • 1
  • 10
  • 16