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 whichfetch
The method is a powerful and flexible tool. This article will introduce in detailfetch
Each aspect of the method helps you better understand and use it.
What is the fetch method
fetch
is a modern API for initiating network requests in JavaScript, which provides a simpler and more powerful way to handle network communications.fetch
Method returns onePromise
Object, thePromise
Will be resolved when the request is completed and aResponse
Object, developers can obtain the server's response data through this object.
Basic syntax
fetch
The 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 (GET
、POST
etc.), request header, request body, etc.
Simple GET request example
The following is a usefetch
An 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 first
fetch
The method initiates a GET request to the specified URL. -
then
The callback function in the method receives aResponse
Object, 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 one
then
The 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 be
catch
Method captures and prints error messages.
Send POST request example
Here is a usefetch
An 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 sent
data
。 - exist
fetch
The second parameter of the methodoptions
The request method specified in isPOST
, set the request headerContent-Type
forapplication/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
Response
Objects 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 intoArrayBuffer
Format, 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
Althoughfetch
It is a modern API, but may not be supported in some older browsers. Can be usedwhatwg-fetch
Wait 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
fetch
Methods will only be rejected if the network error (such as the server cannot be connected)Promise
, for HTTP errors (such as 404, 500, etc.),Promise
Will 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 itAbortController
Object
//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
fetch
Methods 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 itfetch
Use 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!