Hello friend,
If you too have ever faced CORS error while building a website like me, then understand – you are not alone!
The first time I saw this error, to be honest, I thought that something big has gone wrong. But then gradually I understood that this is actually a security shield – and a very important one too.
Today I want to share the same things with you with an open heart
Imagine a little thing…
Suppose you log in to your bank’s website (say bank.com).
Now your browser knows that you are logged in, because a session cookie is saved in it.
Now in the meantime, you click on a strange email which takes you to attack.com.
This website now silently sends a request from your browser to bank.com – and the bank thinks that this request is yours, because the cookie is yours!
And lo and behold – the bank’s data went straight to the attacker website.
Then came the Same-Origin Policy (SOP)
People saw that this was very dangerous, so browsers created a rule — SOP
This rule said, “If a website requests data from another origin (meaning another website), we will block it.”
Simple and clear — but this rule was so strict that even public APIs and third party services couldn’t work.
Then came CORS – a little smartness
The browser said, “Okay, if a website is asking for data from another origin, we will send a header called Origin.”
For example:
Origin: http://example.com
Now the server decides if it wants to respond or not.
If the server says – “yes, this website looks trustworthy to me”, it sends this header:
Access-Control-Allow-Origin: http://example.com
And if this information is public to everyone, it uses *.
Going a little deeper – Preflight
Now imagine that a request is via a specific method like PUT or DELETE, or has specific headers.
The browser first asks:
"Sir, can I send this request?"
And this is done via an OPTIONS method – which we call a preflight request.
If the server replies – "Yes, send!" and returns the correct headers, then the actual request is sent.
Now let's talk about the real issue
Look friend, this is not just about code - it's about our security.
CORS is a browser's intelligence, which prevents your data from falling into the wrong hands.
But yes, it is effective only when you are using a trusted browser (like Chrome, Firefox).
If you use a third party or unsecured browser, then all this hard work will go to waste.
From my experience...
When I was building a new website, this CORS error was very annoying.
But as I understood it, I realized that it is not a technical obstacle, but an honest guard - who keeps my and my users' data safe.