Fixing a CORS Error in Rails
One of the biggest errors I got when I first started building web applications was a Cors Error. I would be happily programming my UI and when I would go to make a REST call to my API. Then BAM. This error….
What Does It Mean?!
In short, CORS is an HTTP-header-based security mechanism that defines who’s allowed to interact with your API. CORS is built into all modern web browsers, so in this case, the “client” is a front-end of the application.
In the most simple scenario, CORS will block all requests from a different origin than your API. “Origin” in this case is the combination of protocol, domain, and port. If any of these three will be different between the front end and your Rails application, then CORS won’t allow the client to connect to the API.
I scoured the internet for HOURS the first time I got this error. Every tutorial was different and none of them seemed to work for me. So, I wanted to show you how I fixed this error and hopefully save a poor soul from going down the same rabbit hole that I did.
First, go into your gem file and make sure that the rack-cors gem is included.
Then, if you are working with rails. Go into config/initializers. Make sure that you have a cors.rb file. If you don’t. Create one!
In the cors.rb, make sure that it looks like one of the images below. Origins ‘*’ is known as a wildcard. In general, it allows anyone on the internet to connect to your API. If you are creating a small project that you don’t intend to deploy, Leaving it as a wildcard (*) will not be a problem. But, If you plan on deploying your application, It is best to specify the domains you only wish to permit and to use credentials to allow for requests.
If you do go with specific origins, when you make a request, you will need to specify the credentials parameter as true when you make frontend requests.
In the example about, I made a request to my Rails backend to login a user and setUser to the response.data
After editing your files. Make sure that you close your application, bundle install, and restart your server to see if that does the trick. Good luck!