JavaScript - Fetch API & HTTP

Overview

Estimated time: 10–15 minutes

The Fetch API provides a modern interface for making HTTP requests in JavaScript, replacing older techniques like XMLHttpRequest.

Learning Objectives

  • Make GET and POST requests using fetch.
  • Handle responses and errors.

Prerequisites

GET Request Example

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

POST Request Example

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 })
})
  .then(response => response.json())
  .then(data => console.log(data));

Common Pitfalls

  • fetch only rejects on network errors, not HTTP errors (check response.ok).

Summary

The Fetch API is the standard for making HTTP requests in modern JavaScript.