Fetch API - Exercise 1
fetch() returns a Promise that fulfills with a Response object.
const response = await fetch('/api/users');
console.log(response.status);Pass the resource URL to fetch(). GET is the default method.
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.
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.
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.
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().
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.
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.
const response = await fetch('/api/data');
const data = await response.json();
// response.text() cannot be called after the body is consumed.