Fetch API

Back

Loading concept...

🌐 HTTP Client and URLs: The Fetch API in Node.js

The Magic Messenger Story

Imagine you have a magic messenger bird 🐦 that can fly anywhere in the world, grab something for you, and bring it back. That’s exactly what the Fetch API does in Node.js! It sends requests across the internet and brings back data.

But wait—what if your bird takes too long? What if you change your mind and want to call it back? That’s where AbortController and AbortSignal come in. They’re like a whistle that lets you call your messenger back anytime!


🎯 What You’ll Learn

  • Fetch API in Node.js — How to send and receive data over the internet
  • AbortController — The “cancel button” for your requests
  • AbortSignal — The messenger that carries your cancel order

📬 Part 1: Fetch API in Node.js

What is Fetch?

Think of fetch() as ordering a pizza online:

  1. You place an order (send a request)
  2. You wait for delivery (the Promise)
  3. Pizza arrives (you get data back)

Your First Fetch

// Ordering data from the internet!
const response = await fetch(
  'https://api.example.com/data'
);

// Unwrap the package
const data = await response.json();

console.log(data);

The Fetch Promise Flow

graph TD A["🚀 Call fetch"] --> B["📤 Request sent"] B --> C["⏳ Waiting..."] C --> D["📥 Response arrives"] D --> E["📦 Parse data"] E --> F["✅ Use data!"]

Fetch with Options

You can customize your request like choosing pizza toppings:

const response = await fetch(url, {
  method: 'POST',      // GET, POST, PUT, DELETE
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Alex',
    age: 25
  })
});

Quick Reference Table

Option What It Does Example
method Type of request 'GET', 'POST'
headers Extra info {'Auth': 'token'}
body Data to send JSON.stringify({})

🛑 Part 2: AbortController

The Problem

What happens when:

  • A request takes too long?
  • The user leaves the page?
  • You don’t need the data anymore?

Without a way to cancel, your messenger bird just keeps flying forever! ❌

The Solution: AbortController

AbortController is like a remote control with a cancel button:

// Create the remote control
const controller = new AbortController();

// Get the signal wire
const signal = controller.signal;

// Press cancel anytime!
controller.abort();

How It Works

graph TD A["🎮 Create Controller"] --> B["📡 Get Signal"] B --> C["🚀 Pass to fetch"] C --> D{Need to cancel?} D -->|Yes| E["🛑 controller.abort"] D -->|No| F["✅ Complete normally"] E --> G["❌ Request cancelled"]

Real Example: Cancel After 5 Seconds

const controller = new AbortController();

// Auto-cancel after 5 seconds
setTimeout(() => {
  controller.abort();
}, 5000);

try {
  const response = await fetch(url, {
    signal: controller.signal
  });
  const data = await response.json();
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request was cancelled!');
  }
}

📡 Part 3: AbortSignal

What is AbortSignal?

If AbortController is the remote control, then AbortSignal is the signal wave it sends. The signal is what actually tells the fetch to stop.

Key Properties

Property What It Tells You
signal.aborted Has cancel been pressed?
signal.reason Why was it cancelled?

Listening for Abort

const controller = new AbortController();
const signal = controller.signal;

signal.addEventListener('abort', () => {
  console.log('Abort detected!');
  console.log('Reason:', signal.reason);
});

// Later...
controller.abort('User cancelled');
// Output: "Abort detected!"
// Output: "Reason: User cancelled"

Built-in Timeout Helper

Node.js gives you a shortcut for timeouts:

// Cancel after 3 seconds automatically!
const signal = AbortSignal.timeout(3000);

try {
  const response = await fetch(url, { signal });
} catch (error) {
  if (error.name === 'TimeoutError') {
    console.log('Too slow! Timed out.');
  }
}

Combining Multiple Signals

What if you want to cancel for multiple reasons?

const userController = new AbortController();
const timeout = AbortSignal.timeout(5000);

// Cancel if EITHER happens
const signal = AbortSignal.any([
  userController.signal,
  timeout
]);

const response = await fetch(url, { signal });

🎯 Putting It All Together

Complete Example: Smart Fetch with Timeout

async function smartFetch(url, timeoutMs) {
  const controller = new AbortController();

  const timeoutId = setTimeout(() => {
    controller.abort('Timeout reached');
  }, timeoutMs);

  try {
    const response = await fetch(url, {
      signal: controller.signal
    });

    clearTimeout(timeoutId);
    return await response.json();

  } catch (error) {
    clearTimeout(timeoutId);

    if (error.name === 'AbortError') {
      throw new Error('Request timed out');
    }
    throw error;
  }
}

// Usage
const data = await smartFetch(
  'https://api.example.com/data',
  5000
);

🧠 Key Takeaways

Concept Remember As
Fetch The messenger bird
AbortController The remote control
AbortSignal The signal wave
abort() The cancel button
AbortSignal.timeout() Auto-cancel timer

🎉 You Did It!

You now understand how to:

✅ Send requests with fetch() in Node.js ✅ Cancel requests using AbortController ✅ Use AbortSignal to detect and handle cancellations ✅ Set timeouts for your requests ✅ Combine signals for complex cancel logic

Your messenger bird is now fully trained—and you have complete control! 🐦✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.