gem "rack-cors" not working and request from angular client to rails api throwing cors error

1.1k Views Asked by At

I am struggling to get gem "rack-cors" to work locally. I have bare rails setup with gem 'devise_token_auth' and angular 7 client with 'angular-token' for auth. But every request from angular is throwing cors error. I have configured rails and "rack-cors" as per documentation but its not working. Here's my configuration in application.rb

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*',
          headers: :any,
          expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
          methods: [:get, :post, :options, :delete, :put]
      end
    end

If I list Middlewares using rails middleware, Rack::Cors is listed second after use Webpacker::DevServerProxy but every request throws following error.

Processing by DeviseTokenAuth::SessionsController#create as HTML
  Parameters: {"session"=>{}}
HTTP Origin header (http://localhost:4200) didn't match request.base_url (http://localhost:3000)
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)



ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
1

There are 1 best solutions below

3
On BEST ANSWER

It turns out I need to change how protect_from_forgery was handled as mentioned in docs

protect_from_forgery with: :null_session

PS: To the person who deleted his answer, please don't do that, knowing what not to do is also part of leaning.