← Cheat Sheets

Fetch API Examples

GET, POST and error handling with fetch.

# Fetch API Examples

GET, POST and error handling with fetch.

```js
// GET
const res = await fetch("https://api.example.com/items?page=1");
if (!res.ok) throw new Error(res.status);
const data = await res.json();

// POST JSON
await fetch("/api/items", {
  method: "POST",
  headers: { "Content-Type": "application/json", Authorization: "Bearer TOKEN" },
  body: JSON.stringify({ name: "Ann" }),
});

// Form data (do not set Content-Type manually)
const fd = new FormData(); fd.append("file", fileInput.files[0]);
await fetch("/upload", { method: "POST", body: fd });

// Timeout
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 5000);
await fetch(url, { signal: ctrl.signal });
```

`fetch` only rejects on network errors. Always check `res.ok`.