JavaScript Fetch API 指南:GET、POST、错误处理与真实案例

1. 介绍

JavaScript 是网页开发中使用最广泛的编程语言之一。在众多特性中,Fetch API 作为实现异步通信的重要能力,受到了广泛关注。

本文将详细阐述 Fetch API——从基础到进阶用法。通过了解它,你将能够在 Web 应用中更流畅地实现数据获取和服务器通信。

什么是异步通信?

异步通信是一种在与服务器交换数据的同时,继续进行其他处理而不阻塞直至通信完成的方法。它提升了用户界面的响应速度,使得处理数据更加轻松,避免了卡顿的困扰。

举例来说,当用户在网页上点击按钮请求数据时,其他任务可以继续进行,而无需等待服务器的响应,从而显著改善用户体验。

什么是 Fetch API?

Fetch API 是 JavaScript 中用于执行异步通信的现代接口。它作为传统 XMLHttpRequest (XHR) 的替代方案被引入,提供了简洁的语法和灵活的配置方式。

使用该 API,你可以轻松编写从服务器获取数据或向服务器发送数据的逻辑。

在接下来的章节中,我们将一步步介绍所有内容——从 Fetch API 的基础用法到实际的真实案例。

2. 什么是 Fetch API?

Fetch API 是 JavaScript 中执行异步通信的最新标准接口。本节将说明它的基本作用以及与传统方式的区别。

Fetch API 概览

Fetch API 旨在通过网络检索资源。
这让 Web 应用能够轻松与服务器进行通信。

关键特性

  • 基于 Promise:无需依赖回调函数,代码更易读。
  • 语法简洁:相较于 XMLHttpRequest,可显著减少代码量。
  • 高度灵活:可以对请求和响应进行细粒度的自定义。
  • 现代设计:与现代 JavaScript 特性配合良好,便于编写可维护的代码。

下面是使用 Fetch API 的基本示例。

fetch('https://api.example.com/data')
  .then(response => response.json()) // Convert to JSON
  .then(data => console.log(data))  // Output the data
  .catch(error => console.error('Error:', error)); // Error handling

该代码从指定 URL 获取数据,将其转换为 JSON,并在控制台输出。若出现错误,则打印错误信息。

与传统 XMLHttpRequest 的区别

Fetch API 是取代广泛使用的 XMLHttpRequest (XHR) 的新方案。下表对两者进行了对比。

FeatureFetch APIXMLHttpRequest
Code simplicityConcise, readable syntaxOften complex with many callbacks
Asynchronous handlingSupports Promises and offers high flexibilityRequires callback functions
Stream processingNative supportRequires additional handling
Working with JSONEasy to handleRequires explicit parsing
Error handlingFlexible and can be centralizedOften becomes complex

如表所示,Fetch API 以其简洁、现代的设计具有很大吸引力。尤其是基于 Promise,使得编写异步逻辑更加自然。

小结

Fetch API 是在 JavaScript 中进行异步通信的强大且易用的工具。由于实现比传统 XHR 更简洁,它已成为现代 Web 开发的必备技能。

在下一节中,我们将通过代码示例逐步演示 Fetch API 的具体使用模式。

3. Fetch API 的基本用法

本节通过具体代码示例说明 Fetch API 的基本用法,主要覆盖以下要点。

  • fetch() 方法的语法及基础示例
  • 如何实现 GET 请求
  • 如何处理响应数据

fetch() 方法的基本语法

使用 Fetch API 时,你可以通过 fetch() 方法向服务器发送请求。下面是基本语法。

fetch(url, options)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });

参数

  • url :请求发送的目标 URL。
  • options(可选):包含 method、headers、body 等设置的选项对象。

返回值

  • Promise 对象:返回异步处理的结果。

如何实现 GET 请求

使用 Fetch API 最基本的方式是 GET 请求,它用于从服务器获取数据。

示例:获取 JSON 数据

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network error');
    }
    return response.json(); // Retrieve data as JSON
  })
  .then(data => {
    console.log(data); // Display the retrieved data
  })
  .catch(error => {
    console.error('Error:', error); // Print an error log
  });

如何处理响应数据

使用 Fetch API,你可以以多种格式处理响应数据。下面列出常见的示例。

  1. 获取文本数据
    fetch('https://example.com/data.txt')
      .then(response => response.text()) // Retrieve data as text
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    
  1. 获取二进制数据
    fetch('https://example.com/image.jpg')
      .then(response => response.blob()) // Retrieve as binary data
      .then(blob => {
        const imgURL = URL.createObjectURL(blob);
        document.querySelector('img').src = imgURL;
      })
      .catch(error => console.error('Error:', error));
    
  1. 获取头部信息
    fetch('https://example.com/api')
      .then(response => {
        console.log(response.headers.get('Content-Type')); // Get a header value
      })
      .catch(error => console.error('Error:', error));
    

小结

本节介绍了使用 Fetch API 发起基本的 GET 请求以及如何处理响应。

Fetch API 是一个灵活的工具,能够轻松获取文本、JSON、二进制等多种数据类型。掌握这些基础后,你将在后续章节(如错误处理和 POST 请求)中更得心应手。

接下来,我们将详细说明如何使用 Fetch API 进行错误处理。

4. 错误处理

本节阐述在使用 Fetch API 时的错误处理方法。与服务器通信时可能会出现网络错误、响应错误等各种问题,妥善处理这些错误可以提升用户体验。

错误处理基础

使用 Fetch API 时,可以通过 catch() 方法捕获网络失败或错误响应等情况。

基础错误处理示例

fetch('https://example.com/data')
  .then(response => {
    if (!response.ok) { // Check the response status code
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error)); // Error handling

使用 try…catch 进行错误处理

结合 Async/Await 可以让代码更简洁、可读。在这种写法中,错误通过 try...catch 语句进行处理。

示例:使用 Async/Await 的错误处理

async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

fetchData();

实现超时机制

Fetch API 默认不提供内置的超时功能。但通过实现超时逻辑,可以对响应缓慢的情况进行适当处理。

示例:实现超时

function fetchWithTimeout(url, timeout = 5000) {
  return Promise.race([
    fetch(url),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timed out')), timeout)
    ),
  ]);
}

fetchWithTimeout('https://example.com/data', 5000)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error));

Detecting network errors

A network error refers to cases where the server cannot be reached or the connection is interrupted. With the Fetch API, these errors can also be detected with catch().

Example: Handling a network error

fetch('https://invalid-url.com/data')
  .then(response => response.json())
  .catch(error => console.error('Network error:', error.message));

Summary

In this section, we introduced error handling with the Fetch API, from basics to more advanced patterns.

Key takeaways

  • Check response status codes and implement error handling
  • Simplify error handling with Async/Await
  • Handle slow responses by implementing timeouts

Error handling is critical for improving the user experience. In the next section, we’ll explain POST requests for sending data to a server.

5. Sending POST requests

In this section, we explain how to send POST requests with the Fetch API to send data to a server. We’ll cover practical examples such as sending form data and JSON.

Basic syntax for POST requests

You can implement a POST request in the Fetch API by providing an options object as the second argument to the fetch() method.

Basic syntax

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Example: Sending JSON data

Below is an example of sending user information in JSON format.

const userData = {
  name: 'Taro Yamada',
  email: 'yamada@example.com',
};

fetch('https://example.com/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(userData),
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Example: Sending form data

To send form data, use the FormData object.

const formData = new FormData();
formData.append('username', 'yamada');
formData.append('file', fileInput.files[0]);

fetch('https://example.com/upload', {
  method: 'POST',
  body: formData,
})
  .then(response => response.json())
  .then(data => console.log('Upload success:', data))
  .catch(error => console.error('Error:', error));

Example: Requests with authentication information

When sending data along with authentication information (for example, a token), add the auth data to the request headers.

fetch('https://example.com/api/protected', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Error handling for POST requests

For POST requests, you can add error handling like the following to deal with network issues or server-side problems.

async function postData(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

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

    const result = await response.json();
    console.log('Success:', result);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

postData('https://example.com/api/messages', { text: 'Hello!' });

Summary

In this section, we explained the basics and practical usage of POST requests using the Fetch API.

Key takeaways

  1. How to send JSON data and form data
  2. How to implement requests with authentication information
  3. How to strengthen error handling

POST requests are essential for two-way communication with servers. In the next section, we’ll explain customization options for the Fetch API in detail.

6. Other option settings

In this section, we explain various option settings you can specify as the second argument to the Fetch API. By using these, you can easily customize requests and manage authentication information.

Basic option syntax

Fetch API options are specified as an object in the second argument.

fetch(url, {
  method: 'GET',              
  headers: {                  
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify(data), 
  credentials: 'include',     
  mode: 'cors',               
  cache: 'no-cache',          
  redirect: 'follow',         
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Details of each option

  1. method (HTTP method)
  • Specifies the HTTP method (for example: GET, POST, PUT, DELETE).
  • The default is GET .
  1. headers (headers)
  • Specifies request headers.
  • Used to define the data format or add authentication information.
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    }
    
  1. body (sending data)
  • Used to send data to the server with POST or PUT methods.
  1. credentials (managing credentials)
  • Controls whether credentials (cookies or HTTP authentication data) are sent.
ValueDescription
omitDo not send credentials (default)
same-originSend credentials only for same-origin requests
includeSend credentials even for cross-origin requests
  1. mode (CORS policy)
  • Controls cross-origin request behavior.
ValueDescription
corsAllow cross-origin requests (default)
no-corsAllow only simple requests (limited)
same-originAllow requests only to the same origin
  1. cache (cache control)
  • Controls how request caching is used.
ValueDescription
defaultUse the browser’s default cache settings
no-storeDo not use cache; always make a new request
reloadIgnore cache and make a new request
  1. redirect (redirect handling)
  • Specifies how redirects are handled.
ValueDescription
followAutomatically follow redirects (default)
errorTreat redirects as errors
manualHandle redirects manually (controllable in code)

Advanced customization example

Below is an example that combines multiple options.

fetch('https://example.com/api/resource', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
  credentials: 'include',
  mode: 'cors',
  cache: 'no-cache',
  redirect: 'follow',
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Summary

In this section, we explained various Fetch API option settings in detail.

Key takeaways

  1. How to customize headers and credentials
  2. Fine-grained settings such as CORS and cache control
  3. Advanced patterns for redirects and error handling

In the next section, we’ll introduce concrete examples of how to use the Fetch API in practice.

7. Practical examples of using the Fetch API

In this section, we explain how you can use the Fetch API in real projects with concrete examples. Through practical scenarios, you’ll build real-world Fetch API skills.

Displaying a list of API data

A common use case in web applications is fetching data from an external API and displaying it as a list. In the example below, we fetch post data from the JSONPlaceholder API and display it as an HTML list.

Code example

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

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(posts => {
    const list = document.getElementById('post-list');
    posts.forEach(post => {
      const listItem = document.createElement('li');
      listItem.textContent = `${post.id}: ${post.title}`;
      list.appendChild(listItem);
    });
  })
  .catch(error => console.error('Error:', error));

HTML example

<ul id="post-list"></ul>

Submitting a form and registering data

This is an example of registering data from a form input to a server.

Code example

const form = document.getElementById('user-form');
form.addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = {
    name: document.getElementById('name').value,
    email: document.getElementById('email').value,
  };

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

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

    const result = await response.json();
    console.log('Registration successful:', result);
    alert('The user has been registered!');
  } catch (error) {
    console.error('Error:', error);
    alert('An error occurred.');
  }
});

HTML example

<form id="user-form">
  <input type="text" id="name" placeholder="Name" required />
  <input type="email" id="email" placeholder="Email address" required />
  <button type="submit">Register</button>
</form>

File upload

The Fetch API can also handle file uploads. Below is an example of uploading an image file to a server.

Code example

const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');

uploadButton.addEventListener('click', async () => {
  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await fetch('https://example.com/upload', {
      method: 'POST',
      body: formData,
    });

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

    const result = await response.json();
    console.log('Upload successful:', result);
    alert('The file has been uploaded!');
  } catch (error) {
    console.error('Error:', error);
    alert('Upload failed.');
  }
});

HTML example

<input type="file" id="file-input" />
<button id="upload-button">Upload</button>

Summary

In this section, we introduced practical examples using the Fetch API.

Key takeaways

  1. Creating a dynamic list by displaying API data
  2. Implementing form submission and data registration
  3. Implementing file uploads and search functionality

By using these examples as references, you can build interactive web applications powered by the Fetch API. In the next section, we’ll summarize the entire article and introduce learning resources for your next steps.

8. Summary

In this article, we explained JavaScript’s Fetch API systematically—from the basics to practical use. The Fetch API is a powerful tool that enables asynchronous communication concisely and efficiently, making it essential for modern web application development.

Review of what you learned

  1. Overview and features of the Fetch API
  • The Fetch API is Promise-based, allowing concise and flexible code.
  • Compared to traditional XMLHttpRequest, the syntax is simpler and easier to maintain.
  1. Basic usage and error handling
  • Basic syntax for fetching data with GET requests.
  • By adding error handling and timeout processing, you can implement more robust code.
  1. Sending data with POST requests
  • 发送 JSON 数据和表单数据的示例。
  • 学习了如何添加身份验证信息和自定义请求头。
  1. 有效使用选项设置
  • 介绍了灵活的自定义方法,如缓存控制、CORS 设置和凭证管理。
  1. 实用示例
  • 通过列表展示、表单提交、文件上传和搜索功能等示例学习了真实的使用场景。

Fetch API 的优势与注意事项

优势

  • 代码简洁且高度可读。
  • 与 Promise 和 Async/Await 配合良好,易于与现代 JavaScript 语法结合。
  • 支持多种数据格式,如 JSON、二进制数据和流。

注意事项

  • 默认没有超时功能,可能需要自行实现。
  • 在旧版浏览器(例如 Internet Explorer)中不受支持,如有需要请考虑使用 polyfill 或替代方案。

下一步学习资源

为了加深对 Fetch API 的理解,请使用下面的官方文档和资源。

最后

Fetch API 是一个强大的工具,使用现代 JavaScript 技术即可轻松实现服务器通信。通过运用本文所学,你可以构建更具交互性和功能丰富的 Web 应用。

随着 Web 开发的不断演进,API 集成和异步处理将变得更加重要。掌握 Fetch API,提升你的实战技能!

后续步骤

  • 尝试创建一个使用真实 API 的项目。
  • 使用自定义选项实现更高级的请求处理。
  • 挑战自己构建与后端服务器集成的全栈应用。

本文到此结束。希望学习 Fetch API 能进一步提升你的技能!

広告