Victor Costa
Victor Costa

Reputation: 25

Rack CORS is working only in a model

I have an Rails 5 App running and I make some requests to populate a front-end. I've activated Rack Cors. It works fine with Notices model but with pages I get it:

Failed to load http://sspmb.com.br/pages.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

But If I try to request .notices.json, It works fine. That's my config/application.rb:

  require_relative 'boot'

  require 'rails/all'

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

  module Sindserv
  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.

  Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
       origins '*'
       resource '/notices',
         headers: :any,
         methods: [:get, :post, :put, :patch, :delete, :options, :head]
       resource '/pages',
         headers: :any,
         methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
  end
    end
  end

Upvotes: 1

Views: 289

Answers (2)

eugene
eugene

Reputation: 550

Enable rack-cors in your gemfile and try this:

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '<your root path>'
    resource '*',
      headers: :any,
      methods: %i(get post put patch delete options head)
  end
end

Upvotes: 1

Can you try this

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

Can you also share logs when the request hits your rails server.

Upvotes: 1

Related Questions