No 'Access-Control-Allow-Origin' header for React.js app

2.2k views Asked by At

I'm trying to delete a user from a simple React.js app. I'm receiving a 302 error and my console displays this error as well.

Fetch API cannot load http://localhost:3001/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise)TypeError: Failed to fetch

My delete request on client side looks like this:

export function deleteUser(id){
  return fetch(`http://localhost:3000/api/v1/users/${id}`, {
    method: 'DELETE'
  }).then( res => res.json() )
}

And the function in the top level container is this:

handleDeleteUser(id){
    localStorage.clear('token')
    deleteUser(id)
    .then((data) => this.setState({
      current_user: data
    }))
  }

I've come across a lot of answers regarding CORS. This is my application.rb file from the server side:

module Our_gardenApi
  class Application < Rails::Application
    config.api_only = true

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

My UsersController is also attempting to redirect like so:

def destroy
  user = User.find(params[:id])
  user.destroy
  redirect_to "http://localhost:3001"
end

The gem 'rack-cors' is also installed within my Gemfile.

In the end, the user is successfully deleted. I'm just running into issues with the redirection. Any help with explanation would be greatly appreciated!

1

There are 1 answers

1
Ashish Jambhulkar On BEST ANSWER

Add this gem into your gem file:

https://github.com/cyu/rack-cors

run bundle install

and then make this configuration in your application.rb file

module YourApp
  class Application < Rails::Application

    # ...

    # Rails 5

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

    # Rails 3/4

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

  end
end