Fetch API - Exercise 1

fetch() returns a Promise that fulfills with a Response object. Handle both network failures and unsuccessful HTTP status codes before using the response data. The example shows where that result becomes available to the rest of the program.

javascript

const response = await fetch('/api/users');
console.log(response.status);

Pass the resource URL to fetch(). GET is the default method. The example shows where that result becomes available to the rest of the program.

javascript

fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json())
  .then(user => console.log(user.name));

Call response.json(); it returns another Promise for the parsed JavaScript value. Handle both network failures and unsuccessful HTTP status codes before using the response data.

javascript

const response = await fetch('/api/data');
const data = await response.json();
console.log(data);

Use response.ok. Fetch does not reject automatically for 404 or 500 responses. The example shows where that result becomes available to the rest of the program.

javascript

const response = await fetch('/api/data');
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);

Wrap the request in try...catch or attach a .catch() handler. Handle both network failures and unsuccessful HTTP status codes before using the response data. The example shows where that result becomes available to the rest of the program.

javascript

try {
  const response = await fetch('/api/data');
  console.log(await response.json());
} catch (error) {
  console.error('Network request failed', error);
}

Call response.text() instead of response.json(). Handle both network failures and unsuccessful HTTP status codes before using the response data. The example shows where that result becomes available to the rest of the program.

javascript

const response = await fetch('/message.txt');
const message = await response.text();
console.log(message);

Update the UI before the request, after success, and in the error path. Handle both network failures and unsuccessful HTTP status codes before using the response data.

javascript

status.textContent = 'Loading...';
try {
  const response = await fetch('/api/data');
  if (!response.ok) throw new Error('Request failed');
  status.textContent = 'Loaded';
} catch {
  status.textContent = 'Could not load data';
}

The body is a stream. Choose the reader you need, such as json() or text(), and do not call both on the same response. If two consumers need the data, parse it once and share the resulting value.

javascript

const response = await fetch('/api/data');
const data = await response.json();
// response.text() cannot be called after the body is consumed.

Create an AbortController, pass its signal to fetch(), and call abort() when the request should stop.

javascript

const controller = new AbortController();
fetch('/api/data', { signal: controller.signal });
controller.abort();

Retry only transient failures, limit the number of attempts, and wait briefly between attempts before giving up.

javascript

for (let attempt = 1; attempt <= 3; attempt++) {
  try { return await fetch('/api/data'); }
  catch (error) { if (attempt === 3) throw error; }
}
All sections expanded. Activate the control to collapse all sections.