1.5K Views

JS111 - Fetch API Basics

Learn how to make HTTP requests in JavaScript using the Fetch API to load data from servers and work with JSON responses.

The Fetch API allows JavaScript to request data from servers.
It is widely used for loading content, submitting forms, and building dynamic web applications.

Basic Fetch Request

A simple request to load JSON data:

fetch("https://example.com/data.json")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

Fetch returns a promise that resolves with a Response object.


Using async/await

Modern JavaScript uses async/await for cleaner syntax:

async function loadData() {
  try {
    const response = await fetch("https://example.com/users");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log("Error: ", error);
  }
}

Sending POST Requests

Fetch can also send data to a server:

fetch("https://example.com/api/create", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Emre",
    age: 30
  })
})

Handling Errors

Fetch does not automatically throw errors for non-200 responses.
You must check status manually.

const response = await fetch(...);
 
if (!response.ok) {
  throw new Error("Request failed");
}

Working With Text Responses

fetch("/hello.txt")
  .then(res => res.text())
  .then(txt => console.log(txt));

Chaining Multiple Fetch Calls

fetch("/api/user")
  .then(res => res.json())
  .then(user => fetch(`/api/posts/${user.id}`))
  .then(res => res.json())
  .then(posts => console.log(posts));

Aborting Requests (AbortController)

const controller = new AbortController();
 
fetch("/slow-request", { signal: controller.signal });
 
controller.abort();

Useful for cancelling long or unwanted requests.


Summary

In this lesson, you learned:

  • How fetch works
  • How to use async/await for cleaner code
  • How to send POST requests
  • How to handle errors
  • How to work with text and JSON responses
  • How to abort fetch requests

In the next lesson, we will explore ES6+ Essentials — modern JavaScript features used in everyday development.