Home Web Front-end JS Tutorial Fetch API Full Guide

Fetch API Full Guide

Dec 04, 2024 pm 04:15 PM

Fetch API Full Guide

Introduction to Fetch API

The Fetch API is a modern, native JavaScript API that allows you to make HTTP requests in a simple and flexible way. It provides an easier and cleaner alternative to older technologies like XMLHttpRequest. Fetch is promise-based, which means it works well with modern JavaScript features such as async/await and .then() chaining.

The Fetch API provides an easy-to-understand way of interacting with RESTful APIs, handling both simple and complex requests. It is widely supported in modern browsers and is a common tool used for web development.

Key Features of Fetch API:

  1. Promise-based: Built on Promises, providing an easy and intuitive way to manage asynchronous code.
  2. Supports all HTTP methods: GET, POST, PUT, DELETE, PATCH, etc.
  3. No callback hell: Thanks to Promises, it avoids nested callbacks.
  4. Stream support: Fetch supports streams, which makes it suitable for handling large amounts of data efficiently.
  5. Improved error handling: Unlike XMLHttpRequest, the Fetch API will not reject an HTTP error status (e.g., 404 or 500). You have to handle these manually.

Installation

The Fetch API is built into modern web browsers, meaning you don’t need to install anything if you’re working in a browser environment. It’s natively available and ready to use for making HTTP requests.

However, if you’re working in a Node.js environment (where fetch is not natively supported), you can install a polyfill such as node-fetch.

1. Using npm (For Node.js environment):

If you’re working in a Node.js environment and need to use Fetch, you can install node-fetch:

npm install node-fetch
Copy after login
Copy after login
Copy after login

Then, import it into your project:

const fetch = require('node-fetch');
Copy after login
Copy after login
Copy after login

Using the Fetch API

The Fetch API provides a global fetch() function that you can use to make HTTP requests. This function returns a Promise that resolves to the Response object representing the response to the request.

Syntax

fetch(url, [options])
Copy after login
Copy after login

Parameters

  1. url:

    • Type: string
    • Description: The URL to which the request is sent. This can be a full URL or a relative URL based on the base URL defined in the request.
  2. options (optional):

    • Type: object
    • Description: An optional configuration object to modify the request. Some common options include:
      • method: The HTTP method (e.g., GET, POST, PUT, DELETE).
      • headers: Custom headers to include in the request (e.g., Content-Type, Authorization).
      • body: The request body (only for methods like POST or PUT).
      • mode: Controls cross-origin requests. (e.g., 'cors', 'no-cors', 'same-origin').
      • cache: Specifies how the request will interact with the cache (e.g., 'no-store', 'reload').
      • credentials: Controls cookies and authentication (e.g., 'same-origin', 'include').

Basic Fetch Request (GET)

A basic GET request with the Fetch API is straightforward. The fetch() function makes a request to the provided URL and returns a Promise that resolves with the Response object.

Example Code:

Here’s an example of a simple GET request using the Fetch API:

npm install node-fetch
Copy after login
Copy after login
Copy after login

Explanation:

  • fetch() initiates the request to the given URL.
  • .then(response => response.json()): Converts the Response object into a JavaScript object by parsing the JSON data.
  • .catch(): Catches and logs any errors, such as network errors or failed requests.

Making POST Requests with Fetch

The Fetch API also allows you to make POST requests. POST requests are typically used for sending data to a server, like submitting a form or creating a new resource.

Syntax for POST Request:

const fetch = require('node-fetch');
Copy after login
Copy after login
Copy after login

Example Code:

Here’s an example of a POST request that sends data to the server:

fetch(url, [options])
Copy after login
Copy after login

Explanation:

  • method: 'POST': Specifies that this is a POST request.
  • body: JSON.stringify(postData): Converts the data to a JSON string before sending it in the request body.
  • headers: Sets the Content-Type header to application/json to indicate that the data being sent is in JSON format.

Handling Response Data

The Response object returned by the Fetch API contains several properties and methods for interacting with the response data.

Key Properties and Methods of Response:

  1. response.json(): Parses the response body as JSON.
  2. response.text(): Parses the response body as a string.
  3. response.blob(): Parses the response as a binary large object (useful for handling images or files).
  4. response.ok: A boolean indicating if the response status code is in the range 200-299 (successful).
  5. response.status: The HTTP status code of the response (e.g., 200 for success, 404 for not found).
  6. response.headers: The headers returned by the server in response to the request.

Example Code:

Here’s an example of how to handle different types of response data:

npm install node-fetch
Copy after login
Copy after login
Copy after login

Explanation:

  • response.ok checks if the response was successful (status code 200-299). If not, an error is thrown.
  • response.json() is called to parse the response as a JavaScript object.

Handling Errors in Fetch

Unlike XMLHttpRequest, the Fetch API does not automatically reject an HTTP error status (e.g., 404 or 500). It only rejects if there’s a network failure or if the request is blocked. To handle errors like 404 or 500, you’ll need to check the response.ok property.

Error Handling Example:

Here’s an example of how to handle errors effectively in Fetch:

const fetch = require('node-fetch');
Copy after login
Copy after login
Copy after login

Explanation:

  • response.ok: This checks if the response status code is in the 200–299 range (indicating success).
  • If the request fails (e.g., 404 or 500 error), it will throw an error with the corresponding status code.

Conclusion

The Fetch API is a powerful and modern tool for making HTTP requests in JavaScript. It provides a clean and intuitive way to work with REST APIs, and its promise-based architecture makes it easy to manage asynchronous code. With its support for all HTTP methods, error handling, and response parsing, Fetch is an essential tool for web developers.

Whether you're fetching data, submitting forms, or handling authentication, the Fetch API offers flexibility and control over your HTTP requests, making it an excellent choice for modern web applications.

The above is the detailed content of Fetch API Full Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles