[Dev] CORS (Cross Origin Resource Sharing)
Introduction
Recently, I have been experiencing an error called CORS or “Cross-Origin Resource Sharing”, while I was developing my full stack application. I have encountered this same problem in the past, and usually used the CORSMiddleware to solve the problem, but I did not have a deep understanding of what CORS stand for. To have a deeper understanding of this, I decided to dive into what CORS really is.
What is CORS?
According to MDN Web Docs, Cross-Origin Resource Sharing(CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
To understand what this definition means, we should first understand what origin is. Origin is defined as the scheme (protocol), hostname (domain), and port of the URL used to access it. Two objects have the same origin only when the scheme, hostname, and port are all the same. To have a better understanding, let’s look at some examples.
- Same : Scheme and host name are the same
- http://example.com/app1/index.html
- http://example.com/app2/index.html
- Same : Both uses the default HTTP Port 80
- http://example.com:80
- http://example.com
- Different : Uses different port numbers
- https://example.com:8080
- https://example.com:3000
When using the Fetch API and XMLHttpRequest, they only allow the same-origin policy. This means that if the frontend and backend are using different origins, they have to use the right CORS headers to request resources from the server. This CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers that have a different origin.
Conclusion
In conclusion, whenever we are writing backend code, we should use the CORS mechanism, if we want our backend server to response to requests that are coming from different origins.