HTTP, CORS and Errors
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
fetchpromise; HTTP errors resolve withresponse.ok === false. - CORS: a page may read a cross-origin response only if the server sends
Access-Control-Allow-Originallowing it. It is enforced by the browser and fixed on the server. - Add a timeout with
fetch(url, { signal: AbortSignal.timeout(5000) }).
HTTP Methods
| Method | Meaning | Has a body | Safe to repeat |
|---|---|---|---|
GET | Read a resource | No | Yes |
POST | Create something, or perform an action | Yes | No (may create duplicates) |
PUT | Replace a resource | Yes | Yes |
PATCH | Change part of a resource | Yes | Not necessarily |
DELETE | Remove a resource | Usually no | Yes |
HEAD | Like GET, headers only | No | Yes |
OPTIONS | Ask what is allowed (used by CORS preflight) | No | Yes |
"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
| Code | Name | Usually means | What your code should do |
|---|---|---|---|
| 200 | OK | Success with a body | Use the data |
| 201 | Created | A POST created something | Use the returned item or its location |
| 204 | No Content | Success with no body | Don't call response.json() (it would fail) |
| 301, 302, 307, 308 | Redirects | Moved; fetch follows automatically | Usually nothing |
| 304 | Not Modified | The cached copy is current | Handled by the browser cache |
| 400 | Bad Request | Invalid input | Show the validation message |
| 401 | Unauthorized | Not logged in | Send the user to log in |
| 403 | Forbidden | Logged in but not allowed | Explain; don't retry |
| 404 | Not Found | No such resource | Show "not found" |
| 409 | Conflict | Conflicts with current state (duplicate, edited by someone else) | Reload and let the user decide |
| 422 | Unprocessable Content | Well-formed but invalid data | Show field errors |
| 429 | Too Many Requests | Rate limited | Wait (see the Retry-After header), then retry |
| 500 | Internal Server Error | Server bug | Show a general error; maybe retry later |
| 502, 503, 504 | Bad Gateway, Unavailable, Gateway Timeout | Server or proxy down or slow | Retry with backoff |
{ "error": "Too many requests. Try again in 30 seconds." }{ "error": "Internal error" }<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>429: slow down (Too many requests. Try again in 30 seconds.)
500: server problem, try later
404: not foundError 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 error | HTTP error | |
|---|---|---|
| Example causes | Offline, DNS failure, connection refused, CORS blocked, aborted | 404, 401, 500... |
fetch promise | Rejects with TypeError (or AbortError/TimeoutError) | Resolves with response.ok === false |
| Handle with | try...catch | if (!response.ok) |
A complete request handles both:
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.
{ "currency": "USD", "rate": 1 }{ "secret": "only for its own site" }<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>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 fetchExplanation: 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:
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: 600Only 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 header | Meaning |
|---|---|
Access-Control-Allow-Origin | Which origin may read the response (* or one exact origin) |
Access-Control-Allow-Methods | Allowed methods (preflight) |
Access-Control-Allow-Headers | Allowed request headers (preflight) |
Access-Control-Allow-Credentials | Whether cookies may be included |
Access-Control-Expose-Headers | Extra 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:
{ "late": true }<script type="module">
try {
await fetch("/api/slow.json", { signal: AbortSignal.timeout(300) });
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>TimeoutError | signal timed outA 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:
{ "students": 3 }<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>OK: {"students":3}
Busy: try again in a moment
Server error: try later
Timed out
Network problem: check your connectionCommon 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
<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>{"students":3}
timeoutKey Takeaways
| Task | Code |
|---|---|
| Handle HTTP errors | if (!res.ok) ... |
| Handle network errors | try { await fetch(...) } catch (err) { ... } |
| Timeout | fetch(url, { signal: AbortSignal.timeout(5000) }) |
| Tell timeouts apart | err.name === "TimeoutError" |
| No body (204) | skip res.json() |
Was this tutorial helpful?