🚦 Cross-Origin Resource Sharing (CORS)

📌 Overview

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers. It allows or blocks web applications running at one origin (domain) from interacting with resources from a different origin.

🚫 The "Same-Origin Policy" (The Villain?)

By default, browsers enforce the Same-Origin Policy. This means a script running on google.com cannot simple fetch data from facebook.com. This prevents malicious sites from stealing your data.

If any of these match, it's the Same Origin. If any differ, it's Cross-Origin.


⚙️ How CORS Works

When your frontend (e.g., React on localhost:3000) tries to call your backend API (e.g., Node.js on localhost:5000), the browser sees different ports and shouts "CROSS ORIGIN ALERT!".

The browser then does steps (typically):

  1. Preflight Request (OPTIONS): The browser sends a polite HTTP OPTIONS request to the backend asking, "Hey, are you okay with localhost:3000 talking to you?"
  2. Server Response: The server must reply with specific headers:
    • Access-Control-Allow-Origin: http://localhost:3000
    • Access-Control-Allow-Methods: GET, POST
  3. Actual Request: If the browser likes the answer, it sends the actual data request.

Architecture Diagram (The Handshake)

      [ Browser ]                          [ API Server ]
      (localhost:3000)                     (better-api.com)
           |                                     |
           |  1. Preflight (OPTIONS)             |
           |  "Can I call you?"                  |
           | ----------------------------------> |
           |                                     |
           |  2. Response (200 OK)               |
           |  "Yes, Allow-Origin: *"             |
           | <---------------------------------- |
           |                                     |
           |  3. Actual Request (GET /data)      |
           | ----------------------------------> |
           |                                     |
           |  4. JSON Data                       |
           | <---------------------------------- |

☁️ CORS in Azure services

You often face CORS errors when building SPAs (Single Page Apps) connecting to Azure services. Here is where you enable it:

  1. Azure Functions:

    • Go to API > CORS in the left menu.
    • Add http://localhost:3000 (or * for testing) to the Allowed Origins list.
  2. Azure App Service:

    • Same procedure. Go to API > CORS.
  3. Azure Storage (Static Website):

    • Since your format is static HTML/JS, if it fetches blobs from another container, you must configure CORS rules on that Blob Service.

💡 Hinglish Explanation (Building Security)

1. Same-Origin Policy (Strict Watchman)

2. CORS (Special Pass)

3. Preflight (Pooch-Taach)


⚡ Exam Tips