Back to roadmaps vanilla-js Course

The Fetch API & HTTP Requests

The Fetch API is a modern browser interface that allows JavaScript to make asynchronous HTTP requests to servers, enabling dynamic page updates without full page reloads (often called AJAX).

1. Making a GET Request

By default, calling fetch() performs a GET request. It returns a Promise that resolves to a Response object.

async function getGithubUser(username) {
  try {
    const response = await fetch(`https://api.github.com/users/${username}`);

    // Parse the response body as JSON
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Network error:", error);
  }
}
getGithubUser("octocat");

2. Handling HTTP Errors Correctly

A common misunderstanding: fetch() only rejects on network failures (such as internet disconnection or DNS resolution failure).

It does not reject on HTTP errors like 404 Not Found or 500 Internal Server Error. Instead, the promise resolves successfully, and you must check the response.ok property:

async function fetchSafe(url) {
  const response = await fetch(url);

  // response.ok is true if status code is in the range 200-299
  if (!response.ok) {
    throw new Error(`HTTP Error! Status: ${response.status}`);
  }

  return await response.json();
}

3. Making POST Requests

To send data to a server (like creating a user account or submitting a form), you must configure fetch() with options:

async function createPost(postData) {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST", // Specify HTTP method
      headers: {
        "Content-Type": "application/json", // Tell server to expect JSON data
        "Authorization": "Bearer token123" // Custom authentication header
      },
      body: JSON.stringify(postData) // Convert JS Object to JSON string
    });

    if (!response.ok) {
      throw new Error("Failed to create post.");
    }

    const result = await response.json();
    console.log("Success:", result);
  } catch (error) {
    console.error(error.message);
  }
}

createPost({ title: "My First JS Post", body: "Hello World!", userId: 1 });

4. Useful Response Methods

The Response object provides several methods to read the payload:

  • response.json(): Parses payload as JSON object.
  • response.text(): Parses payload as plain text.
  • response.blob(): Parses payload as a raw binary file (useful for downloading files/images).

In the next module, we will explore ES6 modules, browser storage mechanisms, and core performance optimization techniques.

Published on Last updated: