If you've ever built a web app that fetches data from an API, there's a good chance you've run into CORS errors. They’re like that annoying bouncer at the club who won’t let you in, even though your friend is already inside waving at you.
So, what is CORS, why does it exist, and how do we deal with it without losing our minds? Let’s break it down.
What Even is CORS?
CORS stands for Cross-Origin Resource Sharing. It’s a security feature built into web browsers that controls which websites (origins) can request resources from another website’s server.
Origins? What’s That?
An origin is simply the protocol + domain + port of a website. For example:
-
https://myapp.com
(origin:https
,myapp.com
, default port443
) -
http://localhost:3000
(origin:http
,localhost
,3000
)
If your frontend is running on http://localhost:3000
and tries to fetch data from https://api.example.com
, that’s a cross-origin request—meaning CORS rules apply.
Why Does CORS Exist?
Think of it as a security guard for your browser. Without CORS, any random website could make requests to your bank, email, or private APIs and steal your data. Not cool.
CORS is the browser’s way of saying:
❌ "Hey, you’re trying to talk to a different website. Are you sure you’re allowed to?"
The server being contacted must explicitly say, “Yes, you are allowed” by including special headers in the response. If it doesn’t, the browser blocks the request.
Common CORS Errors & Fixes
Now, let’s talk about those frustrating CORS errors and how to deal with them.
🚨 Error: No ‘Access-Control-Allow-Origin’ header
💡 What’s happening?
Your frontend made a request to another domain, but the server didn’t include an Access-Control-Allow-Origin
header.
🛠 How to fix it:
- If you own the API, update the backend to send the header:
Access-Control-Allow-Origin: *
🚨 Error: Preflight request blocked
💡 What’s happening?
Some requests (like POST, PUT, or requests with custom headers) trigger a preflight request. The browser first sends an OPTIONS request to check if the API allows it. If the API doesn’t respond correctly, the main request is blocked.
🛠 How to fix it:
Make sure the server handles OPTIONS requests and responds with:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type
```
`
(This tells the browser, “Yes, I accept these request types.”)