2

I have a react app running on localhost:3001 and a rails 6 api backend on localhost:3000

I keep getting cors errors when I post from react to rails. The rails app has Rack Cors.

I've tried adding this to cors.rb in the initializers folder.

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end
end

It didn't work, I also tried to add it to application.rb and config.ru. Noting has worked, and I am confused.

Peter McKinney
  • 292
  • 2
  • 12
  • What does your post request look like? – Ibraheem Ahmed May 18 '20 at 00:23
  • something like this { "auth": { "email":"test@mail.com", "password":"test" } } – Peter McKinney May 18 '20 at 15:28
  • I am facing the same issue. I unfortunately don't have a solution at the moment, but it seems there might be a bug in the latest version of the rack-cors gem that makes it reject whitelisted domains in Rails 6. It is mentioned in [this article](https://levelup.gitconnected.com/api-authentication-with-jwt-and-cookies-featuring-rails-6-and-react-bd33a477c559), where they recommend pinning rack-cors to ~> 0.4.1 (that did not work for me). There is also [this issue](https://github.com/cyu/rack-cors/issues/203) where the OP stated it did not work on a new Rails 6 project but worked when running rai – skyshell May 19 '20 at 15:47
  • 1
    @PeterMcKinney did you find any solution to this? – Talha Meh Apr 24 '21 at 15:08

1 Answers1

0
allow do
 origins '*'
 resource '*', :headers => :any, :methods => :any
end

if this will not work try putting

origins 'localhost:3001'

Hope it helps

Ahmad
  • 428
  • 2
  • 7
  • 1
    unfortunately not, thanks though, that stopped all methods. including get – Peter McKinney May 17 '20 at 23:18
  • then try to put origins 'localhost:3001' in your code only – Ahmad May 17 '20 at 23:21
  • 1
    no, no luck. `Access to XMLHttpRequest at 'localhost:3000/user_token' from origin 'http://localhost:3001' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.` – Peter McKinney May 17 '20 at 23:31