When I call any API is getting a response CORS error for rails API

1.4k views Asked by At

I am trying to configure the back-end with the front-end while they are running two different ports. I send a request to it from an app (on a different subdomain than the API) I get the following response:

Access to XMLHttpRequest at 'http://localhost:3000/api/products?desc=true&tab=Competition&trending=false&page=1' from origin 'http://localhost:3001' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I don't understand why this is happening, since I have already set up Rack CORS Middleware.

CROS configuration as follows:

Gemfile: gem 'rack-cors'

config/initializers/cors.rb:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    # TODO: add only authorized url address
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :patch, :put]
  end
end

For reference, I have attached a browser error screenshot. enter image description here

enter image description here

Preflight request: enter image description here

Preflight response body enter image description here

Ajax request :

export const fetchProducts = () => (dispatch) => {
  // dispatch(requestProducts())
  const data = { desc: true, tab: 'My Products', trending: false }
  $.ajax({
    method: 'get',
    url: `http://localhost:3000/api/products?desc=true&tab=Competition&trending=false&page=1`,
    // csrfToken,
    xhrFields: {
      withCredentials: true
    },
    success(response) {
      console.log(response)
      // dispatch(receiveProducts(response));
    },
    error(xhr) {
      console.log(xhr)
      // dispatch(receiveServerErrors(xhr));
    }
  })
}

Thank You

1

There are 1 answers

0
Reza Khani On

You should try to set the response header key "access-control-allow-credentials" to be true with a specific origin. Like the code below:

# config/initializers/cors.rb

require 'rack/cors'

Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins 'http://localhost:3000'
      resource '*', headers: :any, methods: [:get, :post, :patch, :put], credentials: true
    end
end