Back to List

fetch API β€” Communicating with a Server

This explains how to send GET/POST requests, process responses, and handle errors using the fetch API.

Beginner
|
5min
|
Verified (2026-07)
Progress0/55 (0%)

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.

javascript
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:

javascript
const res = await fetch("/api/users");
const users = await res.json();

If you need query parameters, append them to the URL:

javascript
const res = await fetch("/api/users?page=2&limit=10");

POST Request

Used to send data:

javascript
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.

javascript
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:

javascript
const res = await fetch("/api/users");
if (!res.ok) {
  throw new Error(`HTTP error: ${res.status}`);
}
const data = await res.json();

Error Handling Pattern

javascript
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

javascript
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

fetch is 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 check res.ok. GET is used to retrieve data, and POST is used to send data.

πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...