𝗪𝗵𝘆 𝗟𝗼𝗰𝗮𝗹𝗵𝗼𝘀𝘁 𝗦𝘁𝗶𝗹𝗹 𝗧𝗿𝗶𝗴𝗴𝗲𝗿𝘀 𝗖𝗢𝗥𝗦 𝗘𝗿𝗿𝗼𝗿𝘀
You run your frontend on localhost:3000. You run your backend on localhost:5000. Both apps live on your laptop. Yet, you see a CORS error.
This happens because of how browsers define an origin.
An origin consists of three parts:
- Protocol
- Domain
- Port
Compare these two:
They share the same protocol. They share the same domain. They use different ports.
Browsers see different ports as different origins.
When your React app calls your API, the browser sees a cross-origin request. It views them as two separate entities.
Why does this rule exist? Security.
If websites could call any API freely, a malicious site could:
- Read your bank data.
- Access private APIs.
- Act on your behalf.
Browsers use the Same-Origin Policy to stop this. Website A cannot access Website B unless Website B says yes.
CORS stands for Cross-Origin Resource Sharing. It is a way for your server to tell the browser: "I trust requests from this specific origin."
You fix this by adding a header to your backend: Access-Control-Allow-Origin: http://localhost:3000
This tells the browser the request is safe.
A common point of confusion: You see the request hit your backend logs, but the frontend fails.
This happens because:
- Frontend sends request.
- Backend receives request successfully.
- Backend sends response successfully.
- Browser receives response and blocks it due to security rules.
The error is a browser security feature.
Tools like Postman or cURL work because they are not browsers. They do not enforce browser security policies.
The browser ignores the fact that both apps sit on your machine. It only cares about the origin.