CORS Basics
Overview
CORS (Cross-Origin Resource Sharing) is a browser security feature.
By default, a web script loaded from https://mywebsite.com is strictly forbidden from making a fetch request to https://google.com/api (a different origin). This prevents malicious scripts from secretly stealing data from other sites on the user's behalf.
To allow a request, the destination server must explicitly send a CORS HTTP Header (Access-Control-Allow-Origin) approving the request.
Syntax
// If you run this from localhost:3000, and the API is on port 8080:
try {
await fetch('http://localhost:8080/secure-data');
} catch (err) {
// If the server doesn't have CORS configured, the browser blocks the read!
// Console Error: "Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present"
}// You CANNOT fix CORS from the Frontend JS!
// The Backend Server (e.g. Node/Express) MUST add this header:
// Express.js Example:
const cors = require('cors');
// Allow requests from our frontend
app.use(cors({ origin: 'http://localhost:3000' }));Common Pitfalls
- Trying to fix a CORS error by changing your frontend
fetchheaders. Beginners waste hours trying to addmode: 'no-cors'to their fetch config. This does NOT bypass the security; it simply makes the response "opaque" (meaning your JS still can't read the data). CORS must be fixed on the SERVER.
Interview Questions
CORS is a protection mechanism enforced entirely by the Client (the Browser) to protect the User. Server-to-server HTTP requests (like cURL or Postman) are not restricted by CORS at all.
Real-World Example
When developing locally, your React app runs on port 3000 and your API on port 5000. Because the ports differ, they are considered 'Cross-Origin', requiring the backend developer to explicitly enable CORS for localhost:3000.
// Backend config
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");Check Your Knowledge
Test your understanding of CORS Basics with these quick questions.