AJAX - CORS (Cross-Origin Resource Sharing),

1) What is CORS?

  • CORS = Cross-Origin Resource Sharing.

  • It’s a browser security feature that allows a web page from one origin (domain) to safely request resources from another origin.

  • Without CORS, the Same-Origin Policy (SOP) blocks cross-domain AJAX requests.


2) How Does CORS Work?

When a browser makes a cross-origin AJAX request, it automatically:

  1. Sends an HTTP request with an Origin header (the domain of the page making the request).

    Origin: https://myapp.com
    
  2. The server responds with CORS headers if it wants to allow the request.

    Access-Control-Allow-Origin: https://myapp.com
    Access-Control-Allow-Methods: GET, POST
    Access-Control-Allow-Headers: Content-Type
    

If the headers match the request, the browser lets JavaScript access the response. Otherwise, it blocks it.


3) Types of CORS Requests

a) Simple Requests

Triggered when using methods like GET or POST with safe headers (e.g., Content-Type: application/x-www-form-urlencoded).

  • Browser sends the request directly.

  • Server must reply with:

    Access-Control-Allow-Origin: https://myapp.com
    

b) Preflighted Requests

Triggered when:

  • Using methods like PUT, DELETE, or PATCH.

  • Using custom headers (e.g., Authorization).

  • Sending JSON (Content-Type: application/json).

The browser first sends a preflight request (OPTIONS method) to ask permission:

Request:

OPTIONS /api/data HTTP/1.1
Origin: https://myapp.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

Response (server must allow it):

Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type

If the preflight succeeds → browser sends the real request.


4) CORS Response Headers (Important)

Header Purpose
Access-Control-Allow-Origin Specifies allowed origins (* or specific domain).
Access-Control-Allow-Methods Allowed HTTP methods (GET, POST, PUT, DELETE…).
Access-Control-Allow-Headers Allowed custom headers (e.g., Authorization).
Access-Control-Allow-Credentials Whether cookies/credentials are allowed.
Access-Control-Expose-Headers Which headers can be accessed by JS.
Access-Control-Max-Age How long the preflight response can be cached.

5) Using CORS in AJAX

Example with fetch()

fetch("https://api.otherdomain.com/data", {
  method: "GET",
  mode: "cors",   // enable CORS mode
  credentials: "include" // include cookies if server allows
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error("CORS error:", err));

If the server doesn’t return the right headers → browser blocks response.


6) Server-Side Examples

Node.js (Express)

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

app.use(cors({ origin: "https://myapp.com", credentials: true }));

app.get("/data", (req, res) => {
  res.json({ msg: "CORS success!" });
});

app.listen(3000);

PHP

header("Access-Control-Allow-Origin: https://myapp.com");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

7) Common Issues with CORS

  1. No CORS headers on server → browser blocks.

  2. Using * with credentials → not allowed; must specify exact origin.

  3. Preflight request denied → server not handling OPTIONS.

  4. Different ports count as different originshttp://localhost:3000http://localhost:5000.


8) Best Practices

  • For public APIs: Access-Control-Allow-Origin: * is fine.

  • For private APIs with cookies: specify exact origin and set

    Access-Control-Allow-Credentials: true
    
  • Always handle preflight (OPTIONS) requests on the server.

  • Avoid over-permissive settings (don’t allow all methods/headers unnecessarily).


Summary

  • CORS is the standard way to bypass Same-Origin Policy.

  • Browser sends Origin, server responds with Access-Control-Allow-*.

  • Simple requests → direct. Complex requests → preflight first.

  • Configure server properly to avoid CORS errors.