Home > Back-end >  CORS Missing Allow Origin React and Rails API
CORS Missing Allow Origin React and Rails API

Time:06-16

my application has in the backend Ruby on Rails and React in the frontend, testing GET and POST Requests in local environment was successfully, during the deployment (Rails API and Heroku and React in Vercel) I'm getting the next error:

missing-cors

I'm using an addons (cors everywhere) in my browser, after activate it this is the result:

cors-everywhere output

So, I would like to manage properly CORS to avoid the use of the addon, as an example this is the frontend code in charge of the GET Request:

  useEffect(() => {
    const fetchMeals = async () => {
      //const response = await fetch('https://movieserp-default-rtdb.firebaseio.com/meals.json');
      const response = await fetch("https://rorletsorder.herokuapp.com/meals", {
        method: 'GET',
      });

      if (!response.ok) {
        throw new Error("something went wrong");
      }

About the backend, the cors.rb is in charge to handle CORS:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  
  #allow do
  #  origins 'localhost:3005', '127.0.0.1:3005'
  #  resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head]
  #end
  allow do
    origins 'https://reactletsorder.vercel.app/'
    resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end

end

As you can see, I have commented the lines when I tested on local and everything works well, the issue is in the deployment, I thought it was more than enough to include the frontend url, my question is: what do I need to change in my back or frontend to manage properly the GET and POST Request without triggering the CORS alert?

Thanks a lot

CodePudding user response:

Directly from the documentation of rack-cors: "When specifying an origin, make sure that it does not have a trailing slash."

So remove the trailing slash from origins 'https://reactletsorder.vercel.app/'

  • Related