Fetching Data with the Fetch API
The fetch API is the standard way to make HTTP requests in modern JavaScript, replacing the older XMLHttpRequest.
async function createPost(data) {
const res = await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
A common surprise: fetch only rejects on network-level failure (like the request never reaching a server). A 404 or 500 response is still a "successful" fetch as far as the promise is concerned — it resolves normally — so you must check res.ok (or res.status) yourself and throw manually when the server reports an error.
A Response object's body can only be read once; calling .json(), .text(), or .blob() a second time on the same response throws, so store the parsed result in a variable if you need to use it more than once.