Fetch API in JavaScript

2026-10-12来源 dev.to JavaScriptEnglish

What Is Fetch API?

The Fetch API is used to send requests to a server and receive data from it.

For example, when we open a website that displays weather information or product details, the website may fetch data from an API.

JavaScript's fetch() method helps us retrieve this data and use it on a webpage.

1. What Is an API?

API stands for Application Programming Interface.

In simple terms, an API allows different software applications to communicate with each other.

For example, a website can use an API to retrieve a list of products from a server instead of storing all the product information directly in its HTML file.

2. Basic Fetch Example

Let's fetch some sample data from a public API.

fetch("https://jsonplaceholder.typicode.com/posts/1") .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.log("Error:", error); }); 

Here is how it works:

  • fetch() sends a request to the API.
  • response.json() reads the response body and converts the JSON data into a JavaScript value.
  • then(data => ...) receives the converted data.
  • catch() handles errors such as network failures.

The request is asynchronous, so JavaScript can continue doing other work while waiting for the response.

3. Displaying API Data on a Webpage

We can use the fetched data to update HTML elements.

HTML:

<h2 id="title">Loading...</h2> <p id="body"></p> 

JavaScript:

fetch("https://jsonplaceholder.typicode.com/posts/1") .then(response => response.json()) .then(data => { document.getElementById("title").textContent = data.title; document.getElementById("body").textContent = data.body; }) .catch(error => { console.log("Error:", error); }); 

Here, the post title and body are displayed on the webpage using the DOM.

4. Where Is Fetch API Used?

The Fetch API is commonly used to:

  • Retrieve product details from a server.
  • Display posts and comments.
  • Get weather information.
  • Load user details.
  • Send data to a server.

原文:https://www.a8q9.cn/en/article/fetch-api-in-javascript-cc758d.html

相关文章