What is CORS?

1. Definition

CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers that restricts web applications from making requests to a different domain (origin) than the one that served the webpage.

2. Why CORS Exists

  • Prevents unauthorized access
  • Protects user data
  • Avoids malicious cross-site requests

3. Example Problem

// Frontend (localhost:3000)
fetch("http://api.example.com/data")

// ❌ Error: Blocked by CORS policy

4. Solution (Enable CORS)

// Using cors package
const express = require("express");
const cors = require("cors");

const app = express();

app.use(cors());

app.get("/", (req, res) => {
  res.send("CORS enabled");
});

app.listen(3000);

5. How it Works

  • Browser sends request to another origin
  • Server responds with CORS headers
  • Browser allows or blocks request based on headers

6. Important Header

Access-Control-Allow-Origin: *

7. Advantages

  • Enhances security
  • Controls API access
  • Prevents unauthorized requests