Home Web Front-end JS Tutorial Introduction to the Fetch API

Introduction to the Fetch API

Feb 15, 2025 am 11:22 AM

Introduction to the Fetch API

Key Points

  • Due to its Promise-based structure, the Fetch API is gradually replacing XMLHttpRequest for network requests, which makes the syntax more concise and avoids callback hell.
  • The
  • fetch() method is defined on the window object. It only requires a required parameter, that is, the URL of the resource to be retrieved, and returns a promise that can be used to retrieve the request's response.
  • The
  • Fetch API allows explicit configuration of request objects, including changing request methods and headers, which can be done by passing a Request object to the fetch() function.
  • Error handling using the Fetch API involves checking the ok property of the Response object, which is true if the response status code is within the range of 200. For network failures, the try...catch block can be used.

This article will introduce the appearance of the new Fetch API, the problems it solves, and the most practical way to retrieve remote data within a webpage using the fetch() function.

For many years, XMLHttpRequest has been a trusted assistant for web developers. Whether used directly or in the background, XMLHttpRequest supports Ajax and a brand new interactive experience, from Gmail to Facebook.

However, XMLHttpRequest is gradually being replaced by the Fetch API. Both can be used to make network requests, but the Fetch API is based on Promise, which makes the syntax more concise and helps avoid callback hell.

Fetch API

The

Fetch API provides a window method defined on a fetch() object that can be used to perform requests. This method returns a Promise that can be used to retrieve the request's response.

The

fetch method has only one required parameter, that is, the URL of the resource to be retrieved. A very basic example is shown below. This will get the first five posts on r/javascript on Reddit:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
  .then(res => console.log(res));
Copy after login
Copy after login
Copy after login

If you check the response in the browser's console, you should see a Response object with multiple properties:

{
  body: ReadableStream
  bodyUsed: false
  headers: Headers {}
  ok: true
  redirected: false
  status: 200
  statusText: ""
  type: "cors"
  url: "https://www.reddit.com/top/.json?count=5"
}
Copy after login
Copy after login
Copy after login

The request seems to have succeeded, but where are our first five posts? Let's find out.

Load JSON

We cannot block the user interface and wait for the request to complete. This is why fetch() returns a Promise, an object that represents future results. In the example above, we use the then method to wait for the server's response and log it to the console.

Now let's see how to extract the JSON payload from that response after the request is completed:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
  .then(res => res.json())
  .then(json => console.log(json));
Copy after login
Copy after login
Copy after login

We start the request by calling fetch(). When promise is finished, it returns a Response object that exposes a json method. In the first then() we can call this json method to return the response body as JSON.

However, the json method also returns a promise, which means we need to link another then() before we can log the JSON response to the console.

Why json() Return a promise? Because HTTP allows you to stream content block by block to client, even if the browser receives a response from the server, the content body may not have arrived yet!

Async...await

.then() The syntax is good, but the simplified way to deal with promises in 2018 is to use the new syntax introduced by ES2017. Using async...await means we can mark the function as async...await, and then use the async keyword to wait for the promise to complete and access the result like a normal object. Asynchronous functions are supported in all modern browsers (except IE or Opera Mini) and Node.js 7.6. await

The following is the above example (slightly extended):

async...await

No big changes. In addition to the fact that we created an asynchronous function (to which we passed the name of the subdirectory), we are now waiting for the result of calling
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
  .then(res => console.log(res));
Copy after login
Copy after login
Copy after login
and then use

again to retrieve JSON from the response. fetch() awaitThis is the basic workflow, but things involving remote services don't always go smoothly.

Processing error

Suppose we request the server that does not exist or that requires authorization. Using

, application-level errors, such as 404 responses, must be handled within the normal process. As mentioned earlier,

returns a Response object with the fetch() attribute. If fetch() is ok, the response status code is in the range of 200: response.ok true

The meaning of the server response code varies by API, and checking
{
  body: ReadableStream
  bodyUsed: false
  headers: Headers {}
  ok: true
  redirected: false
  status: 200
  statusText: ""
  type: "cors"
  url: "https://www.reddit.com/top/.json?count=5"
}
Copy after login
Copy after login
Copy after login
is usually not enough. For example, some APIs return 200 responses even if the API key is invalid. Be sure to read the API documentation!

response.okTo handle network failures, use

Block:

try...catch

The code in the
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
  .then(res => res.json())
  .then(json => console.log(json));
Copy after login
Copy after login
Copy after login
block will only run when a network error occurs.

catchYou have learned the basics of making requests and reading responses. Now let's customize the request further.

Change request method and header

View the example above, you may be wondering why you can't just use the existing XMLHttpRequest wrapper. The reason is that the Fetch API provides more than just

methods.

fetch()While the same XMLHttpRequest instance must be used to perform request and retrieve responses, the Fetch API allows you to explicitly configure the request object.

For example, if you need to change how

makes a request (for example, configure a request method), you can pass a Request object to the

function. The first parameter of the Request constructor is the request URL, and the second parameter is the option object for configuring the request: fetch()

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
  .then(res => console.log(res));
Copy after login
Copy after login
Copy after login

Here, we specify the request method and ask it to never cache the response.

The request header can be changed by assigning the Headers object to the request header field. Here is how to request JSON content using only the "Accept" header:

{
  body: ReadableStream
  bodyUsed: false
  headers: Headers {}
  ok: true
  redirected: false
  status: 200
  statusText: ""
  type: "cors"
  url: "https://www.reddit.com/top/.json?count=5"
}
Copy after login
Copy after login
Copy after login

New requests can be created from old requests to adjust their purpose. For example, you can create a POST request from a GET request to the same resource. Here is an example:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
  .then(res => res.json())
  .then(json => console.log(json));
Copy after login
Copy after login
Copy after login

Response headers can also be accessed, but remember that they are read-only values.

async function fetchTopFive(sub) {
  const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
  const fetchResult = fetch(URL);
  const response = await fetchResult;
  const jsonData = await response.json();
  console.log(jsonData);
}

fetchTopFive('javascript');
Copy after login

Request and Response closely follow the HTTP specification; you should know them if you have ever used a server-side language. If you are interested in learning more, you can read all the relevant information on the Fetch API page on MDN.

Integrate all content

To end this article, here is a runnable example demonstrating how to get the first five posts of a specific subdirectory and display their details in the list.

(The CodePen example should be inserted here, but since I can't access the external website, it cannot be provided)

Next steps

In this article, you have learned about the appearance of the new Fetch API and the issues it solves. I've demonstrated how to use the fetch() method to retrieve remote data, how to handle errors, and how to create a Request object to control request methods and headers.

As shown in the chart below, support for fetch() is good. If you need to support older browsers, you can use polyfill.

(Can I Use fetch? chart should be inserted here, but since I can't access external websites, it cannot be provided)

Therefore, the next time you make an Ajax request using a library such as jQuery, please take some time to consider whether you can use the native browser method.

Frequently Asked Questions about Fetch API (FAQ)

(The FAQ part should be included here, but due to space limitations, I will omit it. You can supplement the FAQ part by yourself based on the previous output.)

The above is the detailed content of Introduction to the Fetch API. 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles