Skip to main content
Quick Guide

Quick Guide

This page condenses the course into a practical reference for everyday AJAX, Fetch, and streaming work.

Decision guide

  • Need a simple request? Use fetch() with async/await.
  • Need upload progress? Use XMLHttpRequest for that flow.
  • Need a very large download? Stream response.body.
  • Need to cancel? Use AbortController.
  • Need partial updates? Use PATCH; full replacement uses PUT.

Minimal request template

async function api(path, options = {}) {
  const response = await fetch(`/api${path}`, {
    credentials: 'same-origin',
    headers: {
      'Accept': 'application/json',
      ...(options.body ? { 'Content-Type': 'application/json' } : {}),
      ...options.headers
    },
    ...options
  });

  if (!response.ok) {
    const detail = await response.text();
    throw new Error(`HTTP ${response.status}: ${detail}`);
  }

  return response.status === 204 ? null : response.json();
}

Method semantics

MethodPurposeBodyIdempotent
GETReadNoYes
POSTCreate or processYesNo
PUTReplaceYesYes
PATCHPartial updateYesUsually no
DELETERemoveOptionalYes

Headers worth knowing

  • Accept - response format you can handle.
  • Content-Type - format of the request body.
  • Authorization - bearer token or scheme credentials.
  • If-None-Match - revalidate against an ETag.
  • If-Match - update only if the resource is unchanged.
  • Retry-After - wait interval for 429 or 503.

Status handling pattern

if (response.status === 401) return signIn();
if (response.status === 403) return showForbidden();
if (response.status === 404) return showMissing();
if (response.status === 422) return showValidation(await response.json());
if (response.status === 429) return scheduleRetry(response);
if (!response.ok) return showFailure(response.status);

Form helpers

function toFormData(object) {
  const form = new FormData();
  for (const [key, value] of Object.entries(object)) {
    if (value !== null && value !== undefined) {
      form.append(key, value);
    }
  }
  return form;
}

Reading a stream

const response = await fetch('/api/logs');
for await (const chunk of response.body.pipeThrough(new TextDecoderStream())) {
  console.log(chunk);
}

Safety checklist

  • Validate and encode every value that reaches a URL.
  • Prefer HttpOnly cookies; keep secrets out of URLs.
  • Include CSRF tokens on cookie-authenticated writes.
  • Escape server data before inserting it into the DOM.
  • Retry idempotent requests only.