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

3
  • 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. Commented Nov 1, 2019 at 3:28
  • 1
    It's nothing to do with reactjs. It's CORS problem, check how to handle it in rails: stackoverflow.com/questions/29751115/… Commented Nov 1, 2019 at 3:29
  • @Benjamin Where i should set that? Commented Nov 1, 2019 at 3:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

As comment said, this is a CORS error.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.