HTTP & AJAX

Communicating with servers using the web platform

HTTP Basics

  • Request = method + URL + headers + optional body
  • Response = status code + headers + body
  • Methods: GET, POST, PUT, DELETE, PATCH; Safe/idempotent vary per method
  • Status: 1xx info, 2xx success, 3xx redirect, 4xx client error, 5xx server error

Headers & Caching

  • Content negotiation: Accept, Content-Type.
  • Caching: Cache-Control (max-age, no-store), ETag, Last-Modified.
  • Compression: Accept-Encoding and Content-Encoding (gzip, br).

CORS

Cross-Origin Resource Sharing controls which origins can access resources.

  • Simple requests include Origin; server replies with Access-Control-Allow-Origin.
  • Preflight for non-simple methods/headers using OPTIONS.
  • Credentials require Access-Control-Allow-Credentials: true and specific origin, not *.

REST & JSON

  • Resource URIs: /users, /users/123.
  • Representations in JSON with media type application/json.
  • Use proper status codes: 200 OK, 201 Created, 204 No Content, 400/404/409, 500.

Fetch API

// GET with error handling
async function getItems(){
  const res = await fetch('https://api.example.com/items');
  if(!res.ok) throw new Error('HTTP '+res.status);
  return res.json();
}

// POST JSON with AbortController
const ac = new AbortController();
setTimeout(()=> ac.abort(), 5000);
fetch('/api/items',{
  method:'POST',
  headers:{'Content-Type':'application/json'},
  body: JSON.stringify({ name:'Book' }),
  signal: ac.signal
}).catch(console.error);
        

XML & DOMParser

Some systems still use XML. Parse and query it like HTML DOM.

const xml = `AdaHello`;
const doc = new DOMParser().parseFromString(xml,'application/xml');
const to = doc.querySelector('to').textContent; // Ada
        

Storage & Cookies

  • localStorage: persistent key-value (per origin).
  • sessionStorage: per-tab lifetime.
  • Cookies: sent with HTTP requests; set HttpOnly, Secure, SameSite.
localStorage.setItem('theme','dark');
document.cookie = 'sid=abc; Path=/; Secure; SameSite=Lax';