Fetch and Network in JavaScript

Introduction

Browsers load data over HTTP with fetch—a Promise-based API for GET/POST JSON, headers, and error handling. This chapter covers basic requests, reading JSON, and patterns that pair with Promises and async/await.

Prerequisites

GET JSON

javascript
// Public demo API — run in browser console or script
async function loadTodo() {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  const data = await response.json();
  console.log(data.title);
}
 
loadTodo();

Check response.ok

javascript
// HTTP 404 still resolves fetch — check status
async function loadUser(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}`);
  }
  return res.json();
}
 
loadUser(1).then(console.log).catch(console.error);
loadUser(9999).catch(console.error);

POST JSON

javascript
async function createPost(title) {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title, userId: 1 }),
  });
  if (!res.ok) throw new Error("create failed");
  return res.json();
}
 
createPost("Hello API").then(console.log);

Headers and CORS

Browsers enforce CORS—your page origin must be allowed by the API server. Public demo APIs permit browser calls; your own backend must send Access-Control-Allow-Origin (or use same-origin routes).

Abort Long Requests

javascript
// Cancel with AbortController
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
 
fetch("https://jsonplaceholder.typicode.com/posts", {
  signal: controller.signal,
})
  .then((r) => r.json())
  .then(console.log)
  .catch((err) => console.error(err.name))
  .finally(() => clearTimeout(timeout));

Mini Example: Load List into DOM

html
<ul id="posts"></ul>
<script>
  async function renderPosts() {
    const list = document.getElementById("posts");
    const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
    const posts = await res.json();
 
    for (const post of posts) {
      const li = document.createElement("li");
      li.textContent = post.title;
      list.appendChild(li);
    }
  }
 
  renderPosts().catch(console.error);
</script>

FAQ

fetch vs XMLHttpRequest?

fetch is modern and Promise-based; XHR remains in legacy code.

Cookies and auth?

Use credentials: "include" for cookies; never embed API secrets in front-end code.

Node.js networking?

Node has fetch (recent versions) and http modules—covered in Node chapters.

What comes next?

Local storage.