CORS ERROR in APIs

Joshua Lingbloom
3 min readJul 20, 2021
CORS: Cross Origin Resource Sharing

If you’ve ever ever worked with an API you know how useful and powerful having access to a database through an API can be, but it can get pretty frustrating when you are not able to get the response you are requesting. The first time I ran into a CORS error I was pretty confused. I was able to get a response from my browser but as soon as I made a fetch request, NOTHING! This costed me many hours of troubleshooting to no avail. But what was the problem?…

Well First we need to look at what CORS is? CORS stands for “Cross Origin Resource Sharing” and is a security mechanic that allows for communication between clients and servers using different domains.

CORS isn’t used when a request is made by a client sharing the same domain as the server. This is because by default “Same Origin Policy” allows data to be shared between client and server of the same domain.

But why does the API request work when putting it into the browser directly? The reason is you are pulling from the correct domain! The browser is pulling directly from the same domain as is in the request. CORS becomes a problem when the incoming response does not have an appropriate “header” that would allow the browser to receive data from a different domain, eg. ‘CORS’.

More often than not CORS is enabled by default to allow for full access to the data despite where the request is coming from, however trouble starts to come when CORS is not enabled, so what are some of the ways we can get around this whole security mechanic?

SOLUTIONS:

CORS can be enabled to allow access from other domains from the servers side by adding the following header on the servers side. This must be added to the response object on the server side and not on the client's side.

By adding this header to the request from the server side this will enable CORS and the request can proceed to the client using a different Domain.

The other method the get around this is to make the request from another server. CORS is a security mechanic that applies to client and server requests and does not apply when servers make requests from another servers. The easiest way to make this server to server request is to use a proxy server and what do you know there’s one that you can use made specifically for this!

http://cors-anywhere.herokuapp.com

By appending this link to the front of your request you will be making it through a server dedicated for making requests to get around responses that don’t have CORS enabled.

“SoftAuthor” has a youtube video that explains how to use both these methods and is a very good source.

https://www.youtube.com/watch?v=gPzMRoPDrFk

Bottom line CORS is a very cool security mechanic that allows for more communications between clients and servers and is not the reason for your grief when requests become denied. CORS is actually just a tool made to help make your life easier.

--

--