iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Web Fetch API

The fetch() API is the modern way to make HTTP requests from JavaScript. It returns a Promise that resolves to a Response object.

GET request

JS
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();

POST with JSON body

JS
const res = await fetch("/api/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
  },
  body: JSON.stringify({ name: "Ada", role: "admin" }),
});
const created = await res.json();

The Response object

Property / methodWhat it gives
res.okTrue for 200–299.
res.status / res.statusTextHTTP status code / message.
res.headers.get("…")Read a response header.
res.json()Parse the body as JSON.
res.text()Read the body as a string.
res.blob()Read as a binary Blob (for downloads).
res.formData()Read as FormData.

Aborting and timeouts

JS
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 5000);

try {
  const res = await fetch("/slow", { signal: ctrl.signal });
} catch (e) {
  if (e.name === "AbortError") console.warn("timed out");
}
Gotcha: fetch() only rejects on network errors. A 404 or 500 still resolves — you must check res.ok yourself.
Tip: Wrap fetch in a tiny helper (api.get, api.post) once per project that throws on non-2xx and handles JSON. Saves a lot of repeated boilerplate.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Web Fetch API!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Send a POST with a JSON body.

fetch('/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON. (payload) });

Test yourself

Q1. A 404 response from fetch causes…
Q2. Cancel a fetch with…
Q3. Parse the response body as JSON with…

Discussion

Loading…