Back
+20 XP
Concept

CORS (Cross-Origin Resource Sharing) Demystified

Browsers enforce the Same-Origin Policy. To allow frontend web apps on `domain-a.com` to call an API on `api.domain-b.com`, the API must reply to `OPTIONS` preflight probes with CORS headers 🌐.

python
# Required CORS Headers for APIs:
cors_headers = {
    "Access-Control-Allow-Origin": "*",  # Or specific origin: 'https://xicae.com'
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Max-Age": "86400"  # Cache preflight response for 24h
}

print(f"CORS Origin Policy: {cors_headers['Access-Control-Allow-Origin']} 🌐")

# 44. CORS (Cross-Origin Resource Sharing) Demystified Browsers enforce the Same-Origin Policy. To allow frontend web apps on `domain-a.com` to call an API on `api.domain-b.com`, the API must reply to `OPTIONS` preflight probes with CORS headers 🌐. ```python # Required CORS Headers for APIs: cors_headers = { "Access-Control-Allow-Origin": "*", # Or specific origin: 'https://xicae.com' "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Max-Age": "86400" # Cache preflight response for 24h } print(f"CORS Origin Policy: {cors_headers['Access-Control-Allow-Origin']} 🌐") ``` CORS is strictly a browser-side security restriction. Bare terminal `curl` or Python scripts bypass CORS entirely because CORS exists to protect end-users in browsers, not servers! 🌐 --- ### Question Which HTTP method does a web browser send as an automatic preflight check before making complex cross-origin requests? 🧠 - [ ] a. `OPTIONS` 🌐 - [ ] b. `HEAD` - [ ] c. `CHECK` - [ ] d. `PROBE` --- ### Challenge Create a dictionary of CORS headers containing `'Access-Control-Allow-Origin': 'https://xicae.org'`. Print whether the origin matches `'https://xicae.org'`. 🎯 <details> <summary>Solution</summary> ```python cors = { "Access-Control-Allow-Origin": "https://xicae.org", "Access-Control-Allow-Methods": "GET, POST, OPTIONS" } print(cors["Access-Control-Allow-Origin"] == "https://xicae.org") ``` </details>

Checkpoint

Which HTTP method does a web browser send as an automatic preflight check before making complex cross-origin requests? 🧠

Practice

Create a dictionary of CORS headers containing `'Access-Control-Allow-Origin': 'https://xicae.org'`. Print whether the origin matches `'https://xicae.org'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks