π CORS (Cross-Origin Resource Sharing) Explained
CORS is a browser security feature that restricts web pages from making requests to a different domain than the one that served the web page. It helps prevent Cross-Site Request Forgery (CSRF) and data theft.
π What Triggers CORS?
A CORS error happens when your frontend JavaScript tries to fetch data from a different origin (domain, protocol, or port) without the proper headers being set on the server.
// Example
fetch("https://api.example.com/data")
.then(res => res.json())
.catch(err => console.error("CORS error:", err));
π Same-Origin Policy
By default, browsers follow the Same-Origin Policy, which blocks reading responses from other origins unless CORS headers are explicitly allowed.
β How to Fix CORS
The server needs to send proper CORS headers. Hereβs how you might fix it depending on the backend:
π’ Node.js (Express)
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors()); // Allow all origins
// OR limit to a specific domain
app.use(cors({ origin: "https://your-frontend.com" }));
π΅ PHP
header("Access-Control-Allow-Origin: *");
// OR for specific origin
header("Access-Control-Allow-Origin: https://your-frontend.com");
βοΈ Preflight Requests
For requests that modify data (e.g., POST, PUT), browsers may send an OPTIONS
request first to check permissions. Your server must respond with:
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Allow-Origin
π« You Can't Bypass CORS on Frontend
CORS is enforced by the browser. You cannot βdisableβ it on the client side. If you're testing locally, use a proxy server or configure the backend to allow localhost.
Access-Control-Allow-Origin
.