On this page
Fetch & Networking
Prev: apis | Up: apis | Next: Storage & State
Rel: Promise & Async, Forms, Validation & Fetch
Ref: MDN Web Docs — Fetch API
Tags: #public #web #platform #apis #networking
Contents
fetch() with Status Check & Timeout
fetch() only rejects on network failures or aborts — not on HTTP 404 or 500 responses. Always check res.ok, and attach AbortSignal.timeout(ms) to bound latency:
async function fetchJson(url, { timeoutMs = 5000 } = {}) {
const res = await fetch(url, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
return res.json();
}
Building Safe URLs (URL & URLSearchParams)
const url = new URL("https://api.example.com/search");
url.searchParams.set("q", "web platform");
url.searchParams.set("page", "1");
console.log(url.href);
Linked from
- tuts/javascript/builtins/json_math_and_date
- tuts/javascript/builtins/promise_and_async
- tuts/javascript/tutorials/event_loop_and_async_programming
- tuts/typescript/tutorials/type_safe_api_clients_and_validation
- tuts/web/apis
- tuts/web/apis/fetch_and_networking
- tuts/web/apis/storage_and_state
- tuts/web/security
- tuts/web/security/same_origin_and_cors
- tuts/web/tutorials/forms_validation_and_fetch
Related notes
- tuts/web/apis Linked here; links to this page; shared tags: #apis, #platform, #web
- tuts/web/apis/storage_and_state Linked here; links to this page; shared tags: #apis, #platform, #web
- tuts/web/tutorials/forms_validation_and_fetch Linked here; links to this page; shared tags: #platform, #web
- tuts/javascript/builtins/promise_and_async Linked here; links to this page; shared tags: #web
- tuts/typescript/tutorials/type_safe_api_clients_and_validation links to this page; shared tags: #apis, #web
- tuts/web/security links to this page; shared tags: #platform, #web
- tuts/web/security/same_origin_and_cors links to this page; shared tags: #platform, #web
- tuts/javascript/builtins/json_math_and_date links to this page; shared tags: #web
- tuts/javascript/tutorials/event_loop_and_async_programming links to this page; shared tags: #web
- tuts/web/apis/observers_and_workers shared tags: #apis, #platform, #web