Complete Guide to JavaScript Fetch API: Basics, Examples, Error Handling, and Security

目次

1. Introduction: What Is the Fetch API?

JavaScript plays a crucial role in front-end development for web applications. Among its many features, the Fetch API is a powerful tool for performing asynchronous communication with servers. In this article, we explain how to use the Fetch API in a beginner-friendly way and introduce its features through practical examples.

What Is the Role of the Fetch API?

The Fetch API is a modern, standard interface for handling HTTP requests and responses. In the past, XMLHttpRequest was commonly used, but the Fetch API offers a simpler and more intuitive design.

Differences Between Fetch API and XMLHttpRequest

The main differences between the Fetch API and the traditional XMLHttpRequest are as follows.

FeatureFetch APIXMLHttpRequest
Code readabilitySimple and intuitiveCallbacks often become complex
Promise supportBuilt-in Promise supportNo native Promise support
Error handlingClearly distinguishes HTTP status and network errorsError handling is more complex
ExtensibilityEasy to configure abort and timeoutRequires additional code

As shown above, the Fetch API is widely used as a more flexible and developer-friendly tool in modern web development.

Common Use Cases for the Fetch API

The Fetch API is commonly used in the following scenarios.

  1. Data retrieval: Fetching user information or post data from APIs.
  2. Data submission: Sending form data or JSON data to a server.
  3. Real-time updates: Receiving dynamic data from a server and updating page content.
  4. External API integration: Connecting with third-party APIs to extend functionality.

For these reasons, the Fetch API has become an essential part of modern JavaScript development.

Summary

In this section, we explained the basic role and advantages of the Fetch API. Compared to the traditional XMLHttpRequest, the Fetch API is more intuitive, easier to use, and Promise-based, making error handling simpler. In the next section, we will explore the basic usage of the Fetch API with concrete code examples.

By continuing, you will learn how to retrieve and manipulate data using the Fetch API in practice.

2. Basic Usage of the Fetch API (With Sample Code)

In this section, we explain the basic usage of the Fetch API using concrete code examples. Even beginners can follow along, starting with a simple GET request.

Basic Fetch API Syntax

The basic syntax of the Fetch API is shown below.

fetch(url, options)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });
  • url: Specifies the request URL.
  • options: Used to configure HTTP methods and headers (optional).
  • then: Handles the response.
  • catch: Handles errors.

Example of a GET Request

Below is a basic example of a GET request.

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('A network error occurred');
    }
    return response.json();
  })
  .then(data => {
    console.log(data); // Display data
  })
  .catch(error => {
    console.error('Error:', error);
  });

Using async/await

With modern JavaScript, you can write cleaner code using async/await.

async function fetchPost() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error('A network error occurred');
    }
    const data = await response.json();
    console.log(data); // Display data
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchPost();

Adding URL Parameters

To include query parameters, write the request as follows.

const userId = 1;
fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Summary

In this section, we covered the basics of making GET requests using the Fetch API.

  • Basic syntax: Simple and easy-to-understand design.
  • Error handling: Supports both network and HTTP errors.
  • async/await: Improves readability and maintainability.
  • URL parameters: Easily implement dynamic conditions.

The next section explains how to process response data returned by the Fetch API in more detail.

3. Response Handling and Data Format Conversion

In this section, we explain how to handle responses retrieved using the Fetch API. We focus especially on converting JSON data and working with text and binary data.

What Is the Fetch API Response Object?

With the Fetch API, the response returned after a request is provided as a Response object.

Main Properties

PropertyDescription
okA boolean value indicating whether the response was successful (HTTP status 200–299).
statusThe HTTP status code (e.g., 200, 404, 500).
statusTextA description of the HTTP status (e.g., OK, Not Found).
headersResponse header information.

Retrieving and Converting JSON Data

With the Fetch API, servers often return data in JSON format.

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

Retrieving Text Data

In some cases, you may need to retrieve data in plain text rather than JSON.

fetch('https://example.com/textfile.txt')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Retrieving Binary Data

To retrieve images or files as binary data, use blob() or arrayBuffer().

fetch('https://example.com/image.jpg')
  .then(response => response.blob())
  .then(blob => {
    const url = URL.createObjectURL(blob);
    document.getElementById('image').src = url;
  })
  .catch(error => console.error('Error:', error));

Summary

In this section, you learned how to handle Fetch API responses and convert data formats.

  • JSON data: Supports the most common server response format.
  • Text and binary data: Retrieve different formats as needed.
  • Response headers: Useful for data management and security checks.

4. Sending POST Requests (With Practical Examples)

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

Basic Syntax for a POST Request

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  • method: Specifies the HTTP method to use (in this case, POST).
  • headers: Specifies the data format (e.g., JSON or form data).
  • body: Converts the data to a string and sends it.

Example: Sending JSON Data

const userData = {
  name: 'Taro Tanaka',
  email: 'taro.tanaka@example.com'
};

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

Example: Sending Form Data

const formData = new FormData();
formData.append('name', 'Taro Tanaka');
formData.append('email', 'taro.tanaka@example.com');

fetch('https://example.com/api/submit', {
  method: 'POST',
  body: formData
})
  .then(response => response.text())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Example: Request With Authentication

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

Summary

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

  • Sending JSON data: Ideal for API integration.
  • Sending form data: Works well for simple forms and file uploads.
  • Authenticated requests: Supports API security requirements.

The next section dives deeper into Fetch API error handling and debugging techniques.

5. Error Handling and Debugging Techniques

In this section, we take a detailed look at error handling and debugging techniques when using the Fetch API.

Common Errors That Occur With the Fetch API

Error TypeCause
Network errorConnection failure to the server, offline state, or request timeout.
HTTP errorHTTP status codes of 400 or higher (e.g., 404, 500).
Data format errorThe response data is not returned in the expected format.
Syntax error (SyntaxError)Invalid JSON data or string parsing errors.
Authentication / authorization errorMissing tokens, invalid credentials, or insufficient access permissions.

Basic Error Handling

fetch('https://jsonplaceholder.typicode.com/posts/9999')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  })
  .catch(error => console.error('Error:', error.message));

Handling Timeouts

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

const timeout = setTimeout(() => controller.abort(), 5000);

fetch('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => response.json())
  .catch(error => {
    if (error.name === 'AbortError') {
      console.error('Timeout: The request was aborted');
    } else {
      console.error('Error:', error.message);
    }
  })
  .finally(() => clearTimeout(timeout));

Debugging Techniques

  1. Logging output:
fetch('https://example.com/api/data')
  .then(response => {
    console.log('Status code:', response.status);
    return response.json();
  })
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Error:', error.message));
  1. Browser developer tools (Network tab):
  • Inspect requests and responses in real time.

Summary

In this section, we explored error handling and debugging techniques for the Fetch API.

  • Common errors: Network errors, JSON parsing errors, and timeout issues.
  • Detailed error handling: Practical examples with clear error handling logic.
  • Debugging: Identify issues using logs and browser developer tools.

The next section explains advanced usage patterns and security measures for the Fetch API.

6. Advanced Usage and Security Measures

In this section, we explain advanced usage techniques and security considerations for the Fetch API.

Aborting Requests (AbortController)

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

fetch('https://jsonplaceholder.typicode.com/posts', { signal })
  .then(response => response.json())
  .catch(error => {
    if (error.name === 'AbortError') {
      console.error('The request was aborted');
    } else {
      console.error('Error:', error.message);
    }
  });

setTimeout(() => controller.abort(), 3000); // Abort after 3 seconds

Requests With Authentication Credentials

const token = 'YOUR_ACCESS_TOKEN';

fetch('https://example.com/api/protected', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Error:', error));

CORS (Cross-Origin Resource Sharing) Support

fetch('https://example.com/api/data', {
  method: 'GET',
  mode: 'cors'
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Summary

In this section, we covered advanced Fetch API usage and security measures.

  • Request abortion: Improve efficiency using AbortController.
  • Authenticated requests: Implement API tokens and CSRF countermeasures.
  • CORS handling: Address cross-origin issues through proper configuration.

7. Common Errors and Troubleshooting (With Summary Table)

In this section, we explain common errors you may encounter when using the Fetch API and how to resolve them.

Common Errors and Their Causes

Error Code / MessageCauseSolution
TypeError: Failed to fetchNetwork issues, incorrect URL, server downtime, or CORS configuration errors.Verify the URL, check network connectivity, and review CORS settings.
SyntaxError: Unexpected token <Invalid JSON format or receiving HTML instead of JSON.Inspect the response as text and verify the returned data format.
404 Not FoundThe specified resource does not exist on the server.Check the URL path and confirm dynamic parameter handling.
500 Internal Server ErrorAn internal server-side error.Review server logs to identify the root cause.

Detailed Error Handling

fetch('https://invalid-url.example.com')
  .then(response => response.json())
  .catch(error => {
    if (error.message.includes('Failed to fetch')) {
      console.error('Network error');
    } else {
      console.error('Other error:', error.message);
    }
  });

Summary

In this section, we reviewed common Fetch API errors and how to handle them.

  • Typical errors: Network errors, JSON format errors, and timeout issues.
  • Detailed handling: Practical examples demonstrating robust error handling.

8. Practical Example: Building a Simple Web App Using API Data

In this section, we explain how to create a simple web application that retrieves data from an external API using the Fetch API.

Preparing the HTML

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Fetch API Sample App</title>
</head>
<body>
  <h1>Post List</h1>
  <button id="fetchButton">Fetch Data</button>
  <ul id="postList"></ul>
  <p id="errorMessage" style="color: red;"></p>

  <script src="app.js"></script>
</body>
</html>

Creating the JavaScript Code

const fetchButton = document.getElementById('fetchButton');
const postList = document.getElementById('postList');
const errorMessage = document.getElementById('errorMessage');

async function fetchPosts() {
  fetchButton.disabled = true;
  errorMessage.textContent = '';
  postList.innerHTML = '';

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    const posts = await response.json();
    posts.forEach(post => {
      const listItem = document.createElement('li');
      listItem.textContent = `${post.id}: ${post.title}`;
      postList.appendChild(listItem);
    });
  } catch (error) {
    errorMessage.textContent = 'Failed to retrieve data.';
  } finally {
    fetchButton.disabled = false;
  }
}

fetchButton.addEventListener('click', fetchPosts);

Summary

In this section, we demonstrated how to build a practical web application using the Fetch API.

  • Core features: Data retrieval and list rendering.
  • Error handling: Displaying user-friendly messages on failure.

9. Conclusion and Next Steps

In this article, we covered the Fetch API comprehensively, from the basics to advanced usage and practical examples. In this final section, we review the key points of each section and suggest what to learn next.

Key Takeaways

Basic Structure and Features of the Fetch API

  • The Fetch API is a powerful interface for performing asynchronous communication with servers in JavaScript.
  • Compared to the traditional XMLHttpRequest, it is simpler, more flexible, and Promise-based, which greatly improves readability.

Data Retrieval and Response Handling

  • We explained how to retrieve JSON, text, and binary data.
  • By using async/await, you can write more intuitive code with simpler error handling.

Data Submission and POST Requests

  • You learned how to send JSON data and form data to a server.
  • Secure requests using authentication tokens were also covered.

Error Handling and Debugging Techniques

  • We introduced practical solutions for network errors and JSON parsing errors.
  • Advanced techniques such as request timeouts and aborting requests were implemented.

Building Practical Web Applications

  • You built a web application that retrieves data from an external API and displays it dynamically in the UI.
  • Through error handling and button state control, you learned design patterns that reflect real-world development scenarios.

Next Steps

To make even better use of the Fetch API, consider learning the following topics.

Advanced API Implementation Techniques

  • Pagination and sorting: Optimize processing when dealing with large datasets.
  • Search functionality: Implement data filtering based on user input.
  • File uploads: Handle image and video uploads.

Security Enhancements

  • OAuth 2.0 and authentication: Understand authentication and authorization processes for secure API connections.
  • CSRF and XSS protection: Implement safer form submissions and defend against malicious scripts.

Integration With Modern Technologies

  • Axios library: A popular alternative to the Fetch API that simplifies HTTP request management.
  • GraphQL: A modern API design model that optimizes data retrieval compared to REST APIs.
  • Real-time communication: Implement real-time data exchange using WebSocket or Server-Sent Events.

Learning Resources

Use the following official documentation and learning resources to further improve your skills.

Final Notes

Through this article, you have gained knowledge and practical skills covering everything from the basics to real-world usage of the Fetch API.

The Fetch API is widely used for tasks ranging from simple data retrieval to complex API integrations. By applying what you have learned here to real projects, you can gain even more practical experience.

Next actions:

  • Build small projects using real APIs to gain hands-on experience.
  • Strengthen error handling and security measures to improve production readiness.
  • Adopt new technologies such as GraphQL and real-time communication to further expand your skill set.
広告