CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers to restrict web pages from making requests to a different domain than the one that served the page.
1️⃣ Why CORS Exists
- Prevents malicious scripts on one site from accessing data on another site without permission.
- Browsers block cross-origin requests unless the server explicitly allows them.
2️⃣ How CORS Works
- When a browser makes a request to a different origin, the server can include CORS headers in the response:
Access-Control-Allow-Origin: https://your-frontend.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
- Preflight requests: For methods like
PUTorDELETEor custom headers, the browser sends an OPTIONS request first to check if the server allows it.
3️⃣ Common CORS Errors
- Blocked by CORS policy → browser blocked request because the server did not send proper headers.
- Happens often in development, e.g., frontend on
localhost:3000calling backend onlocalhost:5000.
4️⃣ How to Resolve CORS Issues
A. Server-Side Fix (Recommended)
- Configure backend to send correct CORS headers.
Node.js Example with Express:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({
origin: "http://localhost:3000", // allow frontend origin
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true // allow cookies/auth headers if needed
}));
app.get("/api/data", (req, res) => {
res.json({ message: "Hello CORS" });
});
app.listen(5000);
B. Using a Proxy (Frontend Workaround)
- For development, configure a proxy to bypass CORS:
- React:
"proxy": "http://localhost:5000"inpackage.json - Sends requests via the same origin → browser allows it
- React:
C. Browser Extensions / Temporary Fix
- Not recommended for production
- Chrome extensions can disable CORS for testing
⚡ Key Takeaways
- CORS is browser-enforced, not a server limitation.
- Always configure the server to allow only trusted origins.
- Preflight requests (
OPTIONS) are automatically handled by the browser. - Using a proxy is convenient for development, not production.
In short:
CORS prevents unauthorized cross-origin requests. To fix issues, configure the backend to send the proper
Access-Control-Allow-*headers or use a development proxy.