What is CORS?

Demetrio Lima
3 min readApr 18, 2021

A simple explanation

Me everytime I try to figure out CORS

I know that I’ve run into issues with CORS but I didn’t quite understand what it was. One of the first times I ran into this issue is when I set up Rails as a Web App but not as an API, so when my Frontend was making requests to my Backend I was getting CORS error Allow-Control-Allow-Origin. At first I did not understand this problem as I didn’t know what was going on. Now that I have a little more understanding post bootcamp I can maybe breakdown why this occurred which can in turn help others to avoid it.

CORS is an acronym for Cross Origin Resource Sharing, this allows for websites outside of the original website to access data from the original website. Most public APIs allow for all users to use GET, HEAD, and OPTIONS in order to access the data inside of there. However, many sites would limit any other data that you need to simply GET in order to avoid data breaching.

CORS is also something that is automatically included in your web browser to help create security from script injecting. You could solve the issue by disabling CORS but I would highly recommend against it unless you’re fully aware of what you’re doing.

Now depending on what language or framework you may set up your CORS policies differently. I’m familiar with how to go about it in Rails, however in order to make this more accessible I’m leaving my code a bit more general.

The code is an example of how you can allow all websites to access your API or website, which is represented by * . If you wanted to narrow down the applications you would replace the *'s with the exact website that will be accessing your information. You can even change the methods to specify which ones you would allow other sites to access.

If you’re running into a CORS error you need to change your headers in the app that you’re trying to access. If you don’t have access to the site’s code then you need to probably change your API keys or other information to allow for yourself to get the code. You can also google enable CORS in [language or framework] someone usually has gone to great lengths to create gems, instructions, or other information for people to make the proper changes.

Resources:

--

--