moves / javascript / fetch json

fetch JSON with error handling

`fetch` only rejects on network failure — a 404 or 500 still resolves. Always check `res.ok` yourself.

#fetch#async#http#json
javascript

async function getUser(id) {
  const res = await fetch(`/api/users/${id}`, {
    headers: { Accept: "application/json" },
  });
  if (!res.ok) {
    throw new Error(`Request failed: ${res.status}`);
  }
  return res.json();
}

// POST with a body
await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Ada" }),
});

Related

WWADD — Choose the tool. Make the move. Build the stack.

FREE REFERENCE · NO LOGINCONTACTPRIVACYTERMS