fetch API β Communicating with a Server
After completing this topic
You will understand the basic pattern for sending requests to a server and processing responses using fetch.
What is fetch?
fetch is an HTTP request function built into the browser. It is used to request or send data to a server. It returns a Promise, so it is often used with async/await.
const response = await fetch("/api/users");
const data = await response.json();
console.log(data);It involves three steps: sending a request β receiving a response β parsing the data.
GET Request
Used to retrieve data. The default is GET, so you don't need to specify it:
const res = await fetch("/api/users");
const users = await res.json();If you need query parameters, append them to the URL:
const res = await fetch("/api/users?page=2&limit=10");POST Request
Used to send data:
const res = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com",
}),
});
const created = await res.json();Pass method, headers, and body as the second argument. The body should contain a string converted using JSON.stringify.
Checking the Response Status
fetch does not throw an error for HTTP errors (404, 500). It only throws an error when the network itself fails.
const res = await fetch("/api/users/999");
console.log(res.status); // 404
console.log(res.ok); // false (status is outside the 200-299 range)Therefore, you need to check it manually:
const res = await fetch("/api/users");
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
const data = await res.json();Error Handling Pattern
async function fetchUsers() {
try {
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (error) {
if (error instanceof TypeError) {
console.log("Network connection failed");
} else {
console.log("Request failed:", error.message);
}
return [];
}
}TypeError occurs when the network itself is unavailable (server down, offline).
Response Data Format
const json = await res.json(); // JSON β object
const text = await res.text(); // text
const blob = await res.blob(); // binary (image, etc.)You can call only one of .json(), .text(), or .blob(). Once the response body has been read, it cannot be read again.
Key Takeaway
fetchis a browser's built-in HTTP request function that returns a Promise. It does not automatically throw an error for HTTP errors (404, 500), so you must checkres.ok. GET is used to retrieve data, and POST is used to send data.