惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
博客园 - 司徒正美
S
SegmentFault 最新的问题
Jina AI
Jina AI
美团技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
小众软件
小众软件
WordPress大学
WordPress大学
爱范儿
爱范儿
博客园 - Franky
量子位
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Fetch API Documentation: A Beginner-Friendly Guide to HTT...
Sushen Santh · 2026-05-16 · via DEV Community

The Complete Guide to JavaScript Fetch API

1. What is the Fetch API?

At its core, the Fetch API is a built-in JavaScript tool for communicating with servers. It allows you to perform CRUD (Create, Read, Update, Delete) operations by connecting your frontend application to a backend server or a third-party API.

Key Capabilities

  • GET: Retrieve data from a server
  • POST: Send new data to a server
  • PUT/PATCH: Update existing data
  • DELETE: Remove data from a server

2. Basic Architecture

The Fetch process follows a simple Request-Response flow:

  1. Client (Browser) sends request using fetch()
  2. Server (API) processes the request
  3. Server sends Response
  4. Data is returned in JSON format

Fetch API Architecture


3. Standard Syntax (Promises)

The basic fetch() method takes one mandatory argument: the URL of the resource you want to fetch. It returns a Promise.

fetch("https://api.example.com/data")
  .then(response => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json(); // Converts response to JSON
  })
  .then(data => {
    console.log("Success:", data); // Handle the data
  })
  .catch(error => {
    console.error("Fetch Error:", error); // Handle errors
  });

Enter fullscreen mode Exit fullscreen mode


4. HTTP Methods in Action

A. GET Request (Retrieve Data)

Used to fetch information. This is the default method for fetch().

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

Enter fullscreen mode Exit fullscreen mode

B. POST Request (Send Data)

Used to create new resources. You must specify the method, headers, and body.

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  },
  body: JSON.stringify({
    title: "New Post",
    body: "Content of the post",
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log("Created:", data));

Enter fullscreen mode Exit fullscreen mode

C. PUT Request (Update Data)

Used to update an existing resource entirely.

fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "PUT",
  headers: {
    "Content-type": "application/json"
  },
  body: JSON.stringify({
    id: 1,
    title: "Updated Title",
    body: "Updated Content"
  })
})
  .then(response => response.json())
  .then(data => console.log("Updated:", data));

Enter fullscreen mode Exit fullscreen mode


5. Modern Approach: Async / Await

Using async/await makes your code look synchronous, cleaner, and much easier to read compared to nested .then() blocks.

async function fetchPosts() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log("Fetched Data:", data);
  } catch (error) {
    console.error("Could not fetch data:", error);
  }
}

fetchPosts();

Enter fullscreen mode Exit fullscreen mode


6. Core Concepts to Remember

Concept Description
API The bridge (Interface) that lets two software talk to each other
JSON A lightweight format for storing and transporting data (JavaScript Object Notation)
Promise An object representing the eventual completion (or failure) of an async operation
Endpoint The specific URL where the API can be accessed

7. Troubleshooting Common Errors

  • 404 Not Found: The URL/Endpoint is incorrect
  • 500 Internal Server Error: Something went wrong on the server's side
  • CORS Error: The server is blocking requests from your domain for security
  • JSON Parsing Error: Occurs if you try to run .json() on a response that isn't valid JSON

Conclusion

The Fetch API is an essential tool for modern web development. Whether you're building a simple blog or a complex web application, understanding how to communicate with APIs is crucial. Start with the basics, practice with public APIs like JSONPlaceholder, and gradually incorporate async/await patterns for cleaner code.

Happy coding!


What's your experience with the Fetch API? Share your thoughts in the comments below!