0

I am using front-end source is ReactJS at port 5555, and my back-end is Rails at port 8888. I was trying to fetch data from Rails at React by using:

const url = 'http://localhost:8888/problems';
fetch(url)
  .then(res => {
    res.json();
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

but I was received the message:

Access to fetch at 'http://localhost:8888/problems' from origin 'http://localhost:5555' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have no idea about that error. Please help me to fix it

Spirit
  • 307
  • 1
  • 3
  • 13
  • You are getting a CORS error from the browser. Your Rails server needs to set the header `Access-Control-Allow-Origin: *`. This is because your webpage and server are technically different origins due to the different ports. – Benjamin Nov 01 '19 at 03:28
  • 1
    It's nothing to do with reactjs. It's CORS problem, check how to handle it in rails: https://stackoverflow.com/questions/29751115/how-to-enable-cors-in-rails-4-app – Jarvan Nov 01 '19 at 03:29
  • @Benjamin Where i should set that? – Spirit Nov 01 '19 at 03:30

2 Answers2

3

Read more about CORS

to fix this, you need rack-cors gem in your Gemfile gem 'rack-cors'

in config/application.rb

# 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

that would suffice for your local right now. You will need to modify it if you deploy your code.

Toh
  • 131
  • 4
0

As comment said, this is a CORS error.

You could fix it according to this question allow-anything-through-cors-policy

Doodle
  • 80
  • 7