0

I have rails app and a react app that makes api call to rails backend for users sigin and registration. My issue is when I make a call from frontend to backend , i get the following error

HTTP Origin header (http://localhost:3006) didn't match request.base_url (http://localhost:3000)

My frontend is hosted in http://localhost:3006, I have created and linked the services using docker container

here is my docker compose

services:
db: 
  image: mysql
  environment:
    MYSQL_ALLOW_EMPTY_PASSWORD: true  
  ports:
    - "3306:3306"
    
frontend:
  image: moindev/moin-blog-frontend:$CI_COMMIT_SHORT_SHA
  ports:
    - "3006:3006"
  command: sh -c "npm install && npm run build && npm start"
    
redis:
  image: redis
  command: redis-server
  ports:
    - "6379:6379"

backend:
  image: moindev/moin-blog-backend:$CI_COMMIT_SHORT_SHA   
  environment:
    BACKEND_URL: "http://backend:3000"
    BACKEND_HOST_NAME: "backend"
    ALLOWED_ORIGIN: "http://localhost:3006"
    google_client_secret: 'GOCSPX-tUcjQRmRs'
    google_client_id: "946502148013-u6hgpl13f8hum1cc"
    jwt_secret_key: 'a6b3c5f5232304609cc28f8e'
  ports:
    - "3000:3000"
  command:    bundle exec rails s -b 0.0.0.0



to resolve the issue i made following changes - I added origins ENV['ALLOWED_ORIGIN'] in application.rb

module Backend
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 7.0
    config.active_job.queue_adapter = :sidekiq
    config.default_url_options = { host: ENV['BACKEND_HOST_NAME'], port: 3000 }
    config.hosts << "ec2-35-1"
    # Configure CORS
    config.middleware.insert_before 0, Rack::Cors do
      allow do
     origins ENV['ALLOWED_ORIGIN'] # replace with the domain(s) you want to allow requests from
        resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end

following is my Cors.rb

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins '*'
      resource(
       '*',
       headers: :any,
       expose: ["Authorization"],
       methods: [:get, :patch, :put, :delete, :post, :options, :show]
      )
    end
  end
Moin Ahmed
  • 49
  • 2
  • 8
  • Suspect this is a duplicate of https://stackoverflow.com/q/65688157/152786 Can you try the various CSRF-related workarounds/fixes in there and report back. – smathy Jul 20 '23 at 20:39
  • Yes , I was able to fix it using origin option in application.rb `config.middleware.insert_before 0, Rack::Cors do allow do origins "localhost" # replace with the domain(s) you want to allow requests from resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end` – Moin Ahmed Jul 21 '23 at 04:18
  • Great, gonna close as a dupe. – smathy Jul 21 '23 at 04:33

0 Answers0