SoFunction
Updated on 2025-04-14

A detailed explanation of fetch method in JavaScript

Preface

In modern web development, data interaction with servers is a common and important task. JavaScript provides a variety of ways to implement this function, among whichfetchThe method is a powerful and flexible tool. This article will introduce in detailfetchEach aspect of the method helps you better understand and use it.

What is the fetch method

fetchis a modern API for initiating network requests in JavaScript, which provides a simpler and more powerful way to handle network communications.fetchMethod returns onePromiseObject, thePromiseWill be resolved when the request is completed and aResponseObject, developers can obtain the server's response data through this object.

Basic syntax

fetchThe basic syntax of the method is as follows:

fetch(url, options)
  .then(response => {
    // Process the response  })
  .catch(error => {
    // Handle errors  });
  • url: Required parameter, indicating the URL of the resource to be requested.
  • options: Optional parameter, is an object containing the request configuration information, such as the request method (GETPOSTetc.), request header, request body, etc.

Simple GET request example

The following is a usefetchAn example of a method to send a simple GET request to get JSON data from the server:

fetch('/todos/1')
  .then(response => {
    // Check whether the response status is 200 - 299    if (!) {
      throw new Error(`HTTP error! status: ${}`);
    }
    // parse the response data into JSON format    return ();
  })
  .then(data => {
    (data);
  })
  .catch(error => {
    ('Fetch error:', error);
  });

Code explanation

  • Call firstfetchThe method initiates a GET request to the specified URL.
  • thenThe callback function in the method receives aResponseObject, pass the inspectionAttribute to determine whether the request is successful. If it fails, throw an error.
  • Then use()The method parses the response data into JSON format, and the method returns a newPromise
  • The second onethenThe callback function in the method receives the parsed JSON data and prints it to the console.
  • If an error occurs during the request process, it will becatchMethod captures and prints error messages.

Send POST request example

Here is a usefetchAn example of method sending POST requests to send JSON data to the server:

const data = {
  title: 'foo',
  body: 'bar',
  userId: 1
};

fetch('/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: (data)
})
  .then(response => {
    if (!) {
      throw new Error(`HTTP error! status: ${}`);
    }
    return ();
  })
  .then(data => {
    (data);
  })
  .catch(error => {
    ('Fetch error:', error);
  });

Code explanation

  • Define an object containing the data to be sentdata
  • existfetchThe second parameter of the methodoptionsThe request method specified in   isPOST, set the request headerContent-Typeforapplication/json, and useMethod converts the data object into a JSON string as the request body.
  • Follow-up processing is similar to GET requests, checking the response status, parsing the response data, and handling possible errors.

Common methods of Response objects

ResponseObjects provide a variety of methods to process response data, and the following are some commonly used methods:

  • (): parses the response data into JSON format.
  • (): parses the response data into text format.
  • (): parses response data into binary large object (Blob) format, which is often used to process binary data such as pictures and audio.
  • (): parse the response data intoArrayBufferFormat, used to process binary data.

For example, use()Method to get text response:

fetch('/')
  .then(response => ())
  .then(text => (text))
  .catch(error => ('Fetch error:', error));

Things to note

Browser compatibility

AlthoughfetchIt is a modern API, but may not be supported in some older browsers. Can be usedwhatwg-fetchWait polyfill to solve compatibility issues.

CORS (cross-domain resource sharing)

If the requested resource is located under a different domain name, the CORS header needs to be configured correctly on the server side, otherwise the request will be blocked by the browser.

Error handling

fetchMethods will only be rejected if the network error (such as the server cannot be connected)Promise, for HTTP errors (such as 404, 500, etc.),PromiseWill still be solved and need to be manually checkedAttributes to handle HTTP errors.

Attachment: Cancel fetch request

  • fetch()After the request is sent, if you want to cancel the request halfway, you need to use itAbortControllerObject
//Create an AbortController instancelet controller = new AbortController();

fetch(url, {
  signal: 
});
//If the bound listen event, the value of the abort event will be triggered if the value of the binding is changed.('abort',
  () => ('abort!')
);
// () method is used to send a cancel signal.  This will trigger the abort event, which can be listened to
(); // Cancel
// You can determine whether the cancel signal has been sent through the attributes(); // true

Example:

//Create an instancelet controller = new AbortController();
//Set the timersetTimeout(() => (), 1000);

try {
  let response = await fetch('path', {
    signal: 
  });
} catch(err) {
  if ( == 'AbortError') {
    ('Aborted!');
  } else {
    throw err;
  }
}

Summarize

fetchMethods provide JavaScript developers with a powerful and flexible way to handle network requests. By usingfetch, can easily send various types of requests such as GET and POST, and process the server's response data. During use, you need to pay attention to browser compatibility, CORS problems and error handling to ensure the stability and reliability of the application. I hope this article can help you better grasp itfetchUse of methods.

This is all about this article about fetch methods in JavaScript. For more related contents of fetch methods in JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!