Repaso
Español

How do you request data from an API in modern JavaScript?

async function loadUser(id) {
  const res = await fetch("/api/users/" + id);
  if (!res.ok) throw new Error("HTTP " + res.status);
  return await res.json();
}

Options

  1. fetch gives a Promise; await it and check res.ok (Correct option)
  2. fetch throws an error on every HTTP error status
  3. res.json() gives the data right away, no await
  4. fetch can only be used to load HTML documents

Answer

fetch returns a Promise; await waits for it; res.json() parses the body; you must check res.ok because fetch does not reject on 404/500

Why

fetch(url) sends an HTTP request and returns a Promise for a Response object.

Important detail: it only rejects on network failure. A 404 or 500 still resolves, so you must check res.ok (or res.status).

res.json() is also asynchronous, it reads and parses the body, so it needs await.

To send data: fetch(url, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(data) }).

Remember

fetch does not reject on HTTP errors: check res.ok.

Key terms

Practice this question in Repaso