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
fetchgives a Promise;awaitit and checkres.ok(Correct option)fetchthrows an error on every HTTP error statusres.json()gives the data right away, noawaitfetchcan 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.