SmartCodingTips

🌐 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.

πŸ’‘ Tip: Use browser DevTools β†’ Network tab to inspect CORS headers like Access-Control-Allow-Origin.