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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
S
SegmentFault 最新的问题
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
博客园 - 叶小钗
The GitHub Blog
The GitHub Blog
MyScale Blog
MyScale Blog
腾讯CDC
博客园 - 聂微东
D
DataBreaches.Net
博客园 - Franky
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
量子位
宝玉的分享
宝玉的分享
D
Docker
T
Tailwind CSS Blog
IT之家
IT之家
Engineering at Meta
Engineering at Meta
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Project Zero
Project Zero
Microsoft Azure Blog
Microsoft Azure Blog
AWS News Blog
AWS News Blog
Google DeepMind News
Google DeepMind News
H
Heimdal Security Blog
W
WeLiveSecurity
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
有赞技术团队
有赞技术团队
Simon Willison's Weblog
Simon Willison's Weblog
NISL@THU
NISL@THU
C
Cybersecurity and Infrastructure Security Agency CISA
Google DeepMind News
Google DeepMind News
T
Threatpost
TaoSecurity Blog
TaoSecurity Blog
N
News and Events Feed by Topic
aimingoo的专栏
aimingoo的专栏
Recent Commits to openclaw:main
Recent Commits to openclaw:main
www.infosecurity-magazine.com
www.infosecurity-magazine.com
SecWiki News
SecWiki News
S
Securelist

DigitalOcean Community Tutorials

It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL How to Use the JavaScript .map() Method Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How To Check If a String Contains Another String in Python How to Read a Properties File in Python Python Command Line Arguments: sys.argv, argparse, getopt Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How to Add and Delete Users on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Reset Your MySQL or MariaDB Root Password How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL How To Use the .htaccess File
How to Use the JavaScript Fetch API
Anish Singh Walia · 2026-06-18 · via DigitalOcean Community Tutorials

Introduction

The JavaScript Fetch API is the built-in way to make HTTP requests in modern browsers and in Node.js 18+. It returns Promises, so you can chain .then() calls or use async/await instead of older patterns like XMLHttpRequest or jQuery’s $.ajax().

In this tutorial, you will send GET and POST requests, handle HTTP errors correctly, cancel slow requests, and compare Fetch with Ajax and Axios.

fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => {
    if (!response.ok) throw new Error(response.status);
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

Deploy your frontend applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Key takeaways

  • The JavaScript Fetch API exposes fetch(url, options). It returns a promise that resolves to a Response object, not parsed JSON.
  • Call response.json(), response.text(), or response.blob() to read the body. Each body-reading method returns its own Promise.
  • fetch() only rejects on network failure. A 404 or 500 response still resolves. Check response.ok or response.status before you parse the body.
  • For POST requests, set method, headers, and body. Use JSON.stringify() when you send JSON. See How to Work with JSON in JavaScript.
  • async/await keeps request code readable. Pair it with try/catch and the same response.ok checks you use in promise chains.
  • AbortController cancels in-flight requests and sets timeouts. Pass signal in the options object.
  • Fetch is built into browsers and Node.js 18+. For interceptors or automatic JSON parsing, many teams pick Axios. See React Axios tutorial for a library-based approach.

Prerequisites

To complete this tutorial, you will need the following:

What is the JavaScript Fetch API?

The JavaScript Fetch API is a browser and Node.js interface for requesting resources over HTTP. You pass a URL (or a Request object) to fetch(). The function returns a Promise that resolves when headers arrive, even when the server returns an error status.

Concept What it means
fetch() Starts an HTTP request. Second arg sets method, headers, body.
Response Metadata plus body readers like .json() and .text().
Request A reusable description of a call you can pass to fetch().

For the full specification, see MDN: Fetch API.

Step 1: Getting started with Fetch API syntax

The simplest call passes only a URL:

fetch(url)

fetch() returns a Promise. Chain .then() to handle a successful response:

fetch(url)
  .then(function() {
    // handle the response
  })

Add .catch() for network errors (offline client, DNS failure, CORS block in some cases):

fetch(url)
  .then(function() {
    // handle the response
  })
  .catch(function() {
    // handle the error
  });

.catch() does not run when the server returns 404 or 500. You handle those status codes inside .then() by checking response.ok. The error handling section below shows the pattern.

Step 2: Use Fetch to get data from an API

This step loads ten users from the JSONPlaceholder API and renders them in an HTML list.

Create authors.html with a heading and an empty list:

authors.html

<h1>Authors</h1>
<ul id="authors"></ul>

Add a script tag. Select the list with getElementById and create a DocumentFragment to hold list items before you attach them to the page:

authors.html

<h1>Authors</h1>
<ul id="authors"></ul>

<script>
  const ul = document.getElementById('authors');
  const list = document.createDocumentFragment();
  const url = 'https://jsonplaceholder.typicode.com/users';
</script>

Call fetch() and check response.ok before you parse JSON:

authors.html

<script>
  const ul = document.getElementById('authors');
  const list = document.createDocumentFragment();
  const url = 'https://jsonplaceholder.typicode.com/users';

  fetch(url)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return response.json();
    })
</script>

The first .then() receives a Response. Calling response.json() returns another Promise with the parsed data. Add a second .then() to build list items with map(), createElement, and appendChild:

authors.html

<script>
  const ul = document.getElementById('authors');
  const list = document.createDocumentFragment();
  const url = 'https://jsonplaceholder.typicode.com/users';

  fetch(url)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return response.json();
    })
    .then((authors) => {
      authors.forEach((author) => {
        const li = document.createElement('li');
        const name = document.createElement('h2');
        const email = document.createElement('span');

        name.textContent = author.name;
        email.textContent = author.email;

        li.appendChild(name);
        li.appendChild(email);
        list.appendChild(li);
      });

      ul.appendChild(list);
    })
    .catch((error) => {
      console.error('Fetch failed:', error);
    });
</script>

This is the complete authors.html file:

authors.html

<h1>Authors</h1>
<ul id="authors"></ul>

<script>
  const ul = document.getElementById('authors');
  const list = document.createDocumentFragment();
  const url = 'https://jsonplaceholder.typicode.com/users';

  fetch(url)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return response.json();
    })
    .then((authors) => {
      authors.forEach((author) => {
        const li = document.createElement('li');
        const name = document.createElement('h2');
        const email = document.createElement('span');

        name.textContent = author.name;
        email.textContent = author.email;

        li.appendChild(name);
        li.appendChild(email);
        list.appendChild(li);
      });

      ul.appendChild(list);
    })
    .catch((error) => {
      console.error('Fetch failed:', error);
    });
</script>

Open the file in a browser. You should see ten author names and email addresses. You just completed a GET request with the JavaScript Fetch API.

Step 3: Handle POST requests

fetch() defaults to GET. For POST, pass a second argument with method, body, and headers.

new-author.js

const url = 'https://jsonplaceholder.typicode.com/users';

let data = {
  name: 'Sammy'
};

let fetchData = {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
};

fetch(url, fetchData)
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return response.json();
  })
  .then((result) => {
    console.log('Created:', result);
  })
  .catch((error) => {
    console.error(error);
  });

JSONPlaceholder echoes your POST body and adds an id field. In a production API, read the status code and response body to confirm the record was saved.

The Headers interface lets you set request and response headers. On the server side, routes map HTTP methods to handler functions. See How To Define Routes and HTTP Request Methods in Express for a Node.js example.

POST with a Request object

You can also build a Request and pass it to fetch():

new-author-request.js

const url = 'https://jsonplaceholder.typicode.com/users';

let data = {
  name: 'Sammy'
};

let request = new Request(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
});

fetch(request)
  .then((response) => response.json())
  .then((result) => console.log(result));

fetch() also supports PUT, PATCH, and DELETE when you set method in the options object.

Step 4: Handle errors with the Fetch API

A resolved fetch() Promise does not mean the request succeeded. The Promise rejects only when the request cannot complete (network down, invalid URL, aborted signal).

Check response.ok (true for status 200–299) or inspect response.status:

fetch('https://jsonplaceholder.typicode.com/posts/999')
  .then((response) => {
    if (!response.ok) {
      return Promise.reject({
        status: response.status,
        statusText: response.statusText
      });
    }
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => {
    console.error('Request failed:', error.status, error.statusText);
  });

For async/await, throw inside try/catch when !response.ok:

async function getPost(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);

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

  return response.json();
}

getPost(1).then(console.log).catch(console.error);

Read Understanding JavaScript Promises for more on chaining and rejection.

Step 5: Fetch with async/await

async/await is syntactic sugar over Promises. It keeps request code flat and easy to read:

async function fetchUsers(endpoint) {
  const response = await fetch(endpoint);

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

  const data = await response.json();
  return data.map((user) => user.name);
}

fetchUsers('https://jsonplaceholder.typicode.com/users')
  .then((names) => console.log(names))
  .catch((error) => console.error(error));

You can return data from an async function and keep chaining .then() on the returned Promise. For a deeper walkthrough of async/await, see Understanding the Event Loop, Callbacks, Promises, and Async/Await in JavaScript.

Step 6: Cancel requests with AbortController

Fetch has no built-in timeout. Use AbortController to cancel a request or stop it after a deadline:

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

fetch('https://jsonplaceholder.typicode.com/users', {
  signal: controller.signal
})
  .then((response) => response.json())
  .then((data) => {
    clearTimeout(timeoutId);
    console.log(data.length, 'users loaded');
  })
  .catch((error) => {
    if (error.name === 'AbortError') {
      console.error('Request timed out');
    } else {
      console.error(error);
    }
  });

AbortController is supported in current versions of Chrome, Firefox, Safari, and Edge, and in Node.js 18+.

Fetch API vs Ajax vs Axios

Feature Fetch API XHR / jQuery Ajax Axios
Installation Native; Node 18+ Native; needs jQuery npm package
Syntax Promise-based Callback or Promise Promise-based
JSON parsing Manual .json() Manual Automatic
HTTP errors Manual response.ok Varies Rejects on 4xx/5xx
Cancellation AbortController xhr.abort() Cancel tokens
Interceptors Not supported Not supported Supported
Interceptors Not supported Not supported Supported

For new projects that already use jQuery, read Submitting AJAX Forms with jQuery for a comparison of $.ajax() and fetch().

Pick Fetch when you want zero dependencies and your team is fine checking response.ok. Pick Axios when you need interceptors, simpler error defaults, or tighter React integration. See How to Use Vue.js and Axios to Display Data from an API.

Using Fetch API in JavaScript frameworks

Fetch API in React

React apps often call fetch() inside useEffect() when a component mounts:

import { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        if (!response.ok) throw new Error(response.status);
        return response.json();
      })
      .then((json) => setData(json))
      .catch((err) => setError(err.message));
  }, []);

  if (error) return <p>Error: {error}</p>;
  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}

export default App;

For a React-focused walkthrough, see How to Call Web APIs with the useEffect Hook in React.

Fetch API in Vue.js

In Vue 3, call fetch() inside onMounted() or the Options API mounted() hook:

<script>
export default {
  data() {
    return { data: null, error: null };
  },
  async mounted() {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!response.ok) throw new Error(response.status);
      this.data = await response.json();
    } catch (error) {
      this.error = error.message;
    }
  }
};
</script>

Many Vue projects use Axios instead. See Vue.js REST API with Axios.

Fetch API in Angular

Angular ships HttpClient for most production apps. You can still call native fetch() in a component when you want a dependency-free call:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-data',
  template: '<p>{{ data | json }}</p>'
})
export class DataComponent implements OnInit {
  data: unknown;

  async ngOnInit() {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    if (!response.ok) throw new Error(String(response.status));
    this.data = await response.json();
  }
}

FAQs

1. What is JavaScript Fetch API?

The JavaScript Fetch API is a built-in interface for making HTTP requests from browser JavaScript and from Node.js 18+. fetch() returns a Promise that resolves to a Response object. You read the body with methods like .json() or .text(). It replaced XMLHttpRequest for most new front-end code.

2. How do you fetch data from an API in JavaScript?

Call fetch() with the API URL, check response.ok, then parse the body:

fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => {
    if (!response.ok) throw new Error(response.status);
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

The same pattern works in Node.js 18+ without extra packages. To test endpoints from the command line, see How to Use Wget to Download Files and Interact with REST APIs.

3. Which is better, Ajax or Fetch?

For new browser code, Fetch is the better default. It is native, Promise-based, and does not require jQuery. Ajax (via XMLHttpRequest or $.ajax()) still fits legacy pages that already depend on jQuery. Fetch gives you a smaller runtime footprint and matches modern async/await style. Ajax wrappers can feel familiar if your codebase already centers on jQuery.

4. What are the disadvantages of Fetch API?

Fetch does not reject on HTTP error status codes, so you must check response.ok yourself. It does not parse JSON automatically, does not include request interceptors, and does not report upload or download progress. Timeouts require AbortController. For apps that need those features out of the box, a library like Axios is often simpler.

5. What is fetch() in JavaScript?

fetch() is the global function that starts a network request. The first argument is a URL string or Request object. The optional second argument is an options object with method, headers, body, and signal. It always returns a Promise. The Promise resolves with response headers even when the server returns an error code.

Conclusion

The JavaScript Fetch API is supported in all current major browsers and in Node.js 18+. You can send GET and POST requests, handle HTTP errors with response.ok, cancel slow calls with AbortController, and write cleaner code with async/await.

For larger projects, compare Fetch with Axios or GraphQL based on how much control you need over errors, caching, and data shape. See An Introduction to GraphQL when you want clients to request only the fields they need.

What’s next

Keep building with these JavaScript tutorials:

Host your API and front end on DigitalOcean App Platform with automatic deploys from GitHub. For a dedicated Node.js server, start with a Droplet and follow How to Set Up a Node.js Application for Production on Ubuntu 22.04.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.