HTTP, CORS and Errors

Updated · 10 min read
mediumES2026javascripthttpcorsfetcherrorsinterview

Every fetch is an HTTP request: a method, a URL, headers and maybe a body, answered by a status code, headers and a body. Understanding the status codes tells you what went wrong and what to do about it. CORS (Cross-Origin Resource Sharing) is the browser rule that decides whether your page may read a response from another origin, and it is behind the most confusing error messages in front-end work. This lesson covers both, plus timeouts, so your requests fail clearly instead of hanging forever.

In One Minute

  • Methods say what you want: GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
  • Status classes: 2xx success, 3xx redirect, 4xx your request was wrong, 5xx the server failed.
  • Network errors reject the fetch promise; HTTP errors resolve with response.ok === false.
  • CORS: a page may read a cross-origin response only if the server sends Access-Control-Allow-Origin allowing it. It is enforced by the browser and fixed on the server.
  • Add a timeout with fetch(url, { signal: AbortSignal.timeout(5000) }).

HTTP Methods

MethodMeaningHas a bodySafe to repeat
GETRead a resourceNoYes
POSTCreate something, or perform an actionYesNo (may create duplicates)
PUTReplace a resourceYesYes
PATCHChange part of a resourceYesNot necessarily
DELETERemove a resourceUsually noYes
HEADLike GET, headers onlyNoYes
OPTIONSAsk what is allowed (used by CORS preflight)NoYes

"Safe to repeat" (idempotent) matters for retries: retrying a failed GET is harmless, but retrying a POST that actually succeeded could record a payment twice. Payment APIs solve this with an idempotency key sent in a header.

Status Codes

CodeNameUsually meansWhat your code should do
200OKSuccess with a bodyUse the data
201CreatedA POST created somethingUse the returned item or its location
204No ContentSuccess with no bodyDon't call response.json() (it would fail)
301, 302, 307, 308RedirectsMoved; fetch follows automaticallyUsually nothing
304Not ModifiedThe cached copy is currentHandled by the browser cache
400Bad RequestInvalid inputShow the validation message
401UnauthorizedNot logged inSend the user to log in
403ForbiddenLogged in but not allowedExplain; don't retry
404Not FoundNo such resourceShow "not found"
409ConflictConflicts with current state (duplicate, edited by someone else)Reload and let the user decide
422Unprocessable ContentWell-formed but invalid dataShow field errors
429Too Many RequestsRate limitedWait (see the Retry-After header), then retry
500Internal Server ErrorServer bugShow a general error; maybe retry later
502, 503, 504Bad Gateway, Unavailable, Gateway TimeoutServer or proxy down or slowRetry with backoff
api/rate-limited.json
{ "error": "Too many requests. Try again in 30 seconds." }
api/server-error.json
{ "error": "Internal error" }
statuses.html
<script type="module">
  async function describe(url) {
    const res = await fetch(url);
    if (res.ok) return `${res.status}: success`;
    const body = await res.json().catch(() => null);
    if (res.status === 404) return "404: not found";
    if (res.status === 429) return `429: slow down (${body?.error})`;
    if (res.status >= 500) return `${res.status}: server problem, try later`;
    return `${res.status}: request rejected`;
  }

  for (const url of ["/api/rate-limited.json", "/api/server-error.json", "/api/nothing.json"]) {
    console.log(await describe(url));
  }
</script>
Output
429: slow down (Too many requests. Try again in 30 seconds.)
500: server problem, try later
404: not found

Error responses often include a JSON body explaining the problem; reading it (carefully, since it might not be JSON) gives users better messages.

Network Errors vs HTTP Errors

Network errorHTTP error
Example causesOffline, DNS failure, connection refused, CORS blocked, aborted404, 401, 500...
fetch promiseRejects with TypeError (or AbortError/TimeoutError)Resolves with response.ok === false
Handle withtry...catchif (!response.ok)

A complete request handles both:

request-json.js
async function requestJson(url, options) {
  let response;
  try {
    response = await fetch(url, options);
  } catch (err) {
    throw new Error("Network problem: check your connection.", { cause: err });
  }
  if (!response.ok) {
    throw new Error(`Server returned HTTP ${response.status}`);
  }
  return response.status === 204 ? null : response.json();
}

What CORS Is

The same-origin policy is a core browser security rule: a page may freely send requests anywhere, but it may only read responses from its own origin (same scheme, host and port). Without it, any website you visit could use your logged-in session to read your email or bank pages.

CORS is the controlled exception. A server can say "pages from these other origins may read my responses" by sending the header Access-Control-Allow-Origin. The browser checks that header and either hands the response to your code or blocks it.

https://api.rates.test/usd.json
{ "currency": "USD", "rate": 1 }
https://api.private.test/data.json
{ "secret": "only for its own site" }
cors.html
<script type="module">
  const allowed = await fetch("https://api.rates.test/usd.json");
  console.log("allowed:", allowed.status, (await allowed.json()).currency);

  try {
    await fetch("https://api.private.test/data.json");
  } catch (err) {
    console.log("blocked:", err.name, err.message);
  }
</script>
Output
allowed: 200 USD
Access to fetch at 'https://api.private.test/data.json' from origin 'https://lesson.test' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://api.private.test' that is not equal to the supplied origin. Have the server send the header with a valid value.
blocked: TypeError Failed to fetch

Explanation: both servers answered. The first sent Access-Control-Allow-Origin: * (anyone may read), so the browser let the page read it. The second allows only its own site (Access-Control-Allow-Origin: https://api.private.test), so the browser blocked the response, printed the detailed reason in the console (the middle line, written by the browser itself), and gave your code only a vague TypeError: Failed to fetch. A server that sends no Access-Control-Allow-Origin header at all is blocked the same way, with the message: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Simple Requests and Preflight

For "simple" requests (GET, HEAD or POST with only basic headers and a form-like content type), the browser sends the request and checks the response's CORS headers. For anything else, such as PUT, DELETE, a JSON Content-Type, or an Authorization header, the browser first sends a preflight request:

A preflight exchange
OPTIONS /api/payments HTTP/1.1
Origin: https://www.fee-tracker.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, authorization
 
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://www.fee-tracker.example
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Max-Age: 600

Only if the preflight answer allows it does the browser send the real request. Access-Control-Max-Age lets the browser cache that answer. For requests with cookies (credentials: "include"), the server must name the exact origin (not *) and send Access-Control-Allow-Credentials: true.

CORS response headerMeaning
Access-Control-Allow-OriginWhich origin may read the response (* or one exact origin)
Access-Control-Allow-MethodsAllowed methods (preflight)
Access-Control-Allow-HeadersAllowed request headers (preflight)
Access-Control-Allow-CredentialsWhether cookies may be included
Access-Control-Expose-HeadersExtra response headers your code may read

Timeouts with AbortSignal.timeout

fetch has no default timeout: a server that never answers leaves the request hanging. AbortSignal.timeout(ms) creates a signal that cancels the request after the given time:

api/slow.json
{ "late": true }
timeout.html
<script type="module">
  try {
    await fetch("/api/slow.json", { signal: AbortSignal.timeout(300) });
  } catch (err) {
    console.log(err.name, "|", err.message);
  }
</script>
Output
TimeoutError | signal timed out

A timeout rejects with a DOMException named TimeoutError, which you can tell apart from a user cancellation (AbortError) and a network failure (TypeError). The cancellation lesson covers AbortController for canceling on demand.

In Practice

The Fee Tracker's API helper classifies every failure so the interface can show the right message: offline, timeout, CORS or network problem, rate limit, or server error:

api/ok.json
{ "students": 3 }
classify.html
<script type="module">
  async function api(url) {
    try {
      const res = await fetch(url, { signal: AbortSignal.timeout(400) });
      if (res.ok) return `OK: ${JSON.stringify(await res.json())}`;
      if (res.status === 429) return "Busy: try again in a moment";
      return res.status >= 500 ? "Server error: try later" : `Request error ${res.status}`;
    } catch (err) {
      if (err.name === "TimeoutError") return "Timed out";
      return "Network problem: check your connection";
    }
  }
  for (const url of ["/api/ok.json", "/api/rate-limited.json", "/api/server-error.json", "/api/slow.json", "https://offline.test/x"]) {
    console.log(await api(url));
  }
</script>
Output
OK: {"students":3}
Busy: try again in a moment
Server error: try later
Timed out
Network problem: check your connection

Common Mistakes

Treating any response as success. Check response.ok or the status.

Trying to fix CORS in the browser. It must be fixed on the server (or by calling through your own server).

Retrying everything. Retry network errors, 429 and 5xx with backoff; don't retry 400, 401, 403 or 404, and be careful retrying POST.

No timeout. A hanging request leaves the user waiting forever. Use AbortSignal.timeout.

Interview Corner

What is CORS?

Cross-Origin Resource Sharing is a browser mechanism that relaxes the same-origin policy. A page may send cross-origin requests, but can only read the response if the server opts in with Access-Control-Allow-Origin (and, for non-simple requests, answers a preflight OPTIONS request with allowed methods and headers). It's enforced by browsers to protect users; servers configure it, and non-browser clients ignore it.

What triggers a CORS preflight?

A cross-origin request that isn't "simple": methods other than GET, HEAD or POST; custom headers such as Authorization; or a Content-Type other than application/x-www-form-urlencoded, multipart/form-data or text/plain (so JSON bodies trigger it). The browser sends OPTIONS first and proceeds only if the response allows the request.

Practice

Challenge: Write fetchWithTimeout(url, ms) that returns the parsed JSON or throws "timeout" when the request takes longer than ms, then test it on /api/ok.json and /api/slow.json.

Show solution
with-timeout.html
<script type="module">
  async function fetchWithTimeout(url, ms) {
    try {
      const res = await fetch(url, { signal: AbortSignal.timeout(ms) });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return await res.json();
    } catch (err) {
      throw new Error(err.name === "TimeoutError" ? "timeout" : err.message);
    }
  }
  console.log(JSON.stringify(await fetchWithTimeout("/api/ok.json", 500)));
  await fetchWithTimeout("/api/slow.json", 200).catch((e) => console.log(e.message));
</script>
Output
{"students":3}
timeout

Quick check: HTTP and CORS

3 questions
1A request returns 503. What kind of problem is it?
2Where is a CORS error fixed?
3What does fetch do by default if the server never responds?

Key Takeaways

TaskCode
Handle HTTP errorsif (!res.ok) ...
Handle network errorstry { await fetch(...) } catch (err) { ... }
Timeoutfetch(url, { signal: AbortSignal.timeout(5000) })
Tell timeouts aparterr.name === "TimeoutError"
No body (204)skip res.json()

Was this tutorial helpful?

Lesson 86 of 139