Skip to content
CORS — Explained with Examples

CORS — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls how web pages request resources from a different origin than their own.

CORS stands for Cross-Origin Resource Sharing. It’s enforced by browsers to prevent malicious websites from reading sensitive data from another site without permission.

The Same-Origin Policy

By default, browsers block JavaScript from making requests to a different origin (protocol + domain + port). https://app.example.com and https://api.example.com are different origins. CORS provides a way to relax this restriction safely.

Browser → Server: "Can I access this resource?"
  Origin: https://myapp.com

Server → Browser: "Yes, but only from myapp.com"
  Access-Control-Allow-Origin: https://myapp.com

Preflight Requests

For requests that modify data (PUT, DELETE, or custom headers), browsers send a preflight OPTIONS request first to check permissions:

// Preflight request (OPTIONS)
OPTIONS /api/users HTTP/1.1
Origin: https://myapp.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: Authorization

// Preflight response
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Access-Control-Max-Age: 86400

Real-World Analogy

Imagine your house has a front door (the browser). You’re inside (your website). Your friend is across the street (another origin). You can shout to your friend (the browser allows it). But if someone on the other side of town tries to shout to you, your friend can’t hear them (same-origin policy). CORS is like giving specific trusted people your phone number.

Server-Side CORS Configuration (Node.js)

const express = require('express');
const cors = require('cors');
const app = express();

// Allow all origins (development only)
app.use(cors());

// Restrict to specific origins
app.use(cors({
  origin: 'https://myapp.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

Related Terms

CSRF, XSS, HTTP, API Gateway, REST

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro