Basic use of fetch
- The Fetch API provides an interface to obtain resources (including cross-domain requests), which replaces the traditional XMLHttpRequest and issues HTTP requests in JavaScript scripts.
- Currently, it is not supported by all browsers. If you consider the problem of lower version browsers, you can use /github/fetch/blob/master/ to be compatible.
- The fetch API is based on promise design and returns a Promise object, which was born to replace the unreasonable writing of traditional xhr.
When there is no fetch, we obtain asynchronous resources like this:
//Send a get request like this: //First instantiate an XMLHttpRequest objectvar httpRequest = new XMLHttpRequest(); //Register a function that will callback when changing, httpRequest.//There are 5 possible values in readyState,//0 UNSENT (not opened) The open() method has not been called yet;//1 OPENED (not sent) The send() method has not been called yet;//2 HEADERS_RECEIVED (Response header has been obtained) The send() method has been called, and the response header and response status have been returned;//3 LOADING (Response Body is being downloaded) The response body is being downloaded; some data has been obtained in responseText;//4 DONE (Request Complete) The entire request process has been completed. = function(){ //The callback function will be called 4 times in sequence (); if(===4){ //The request has been completed if(===200){ //http status is 200 (); var data = (); (data); } } } //Requested URLvar url = '/users/ruanyf';; //This method is an initialization request. The first parameter is the requested method, such as GET, POST, PUT, and the second parameter is the requested url.('GET',url,true); //Set http request header("Content-Type","application/json"); //Send a request, the parameter is the body to be sent. If it is a GET method, generally there is no need to send a body, set it to empty(null);
If fetch is used, send a get request like this:
//Requested URLvar url = '/users/ruanyf';; //Stack get requestvar promise = fetch(url).then(function(response) { //http status code indicating the response if( === 200){ //json is a method provided by the returned response, which will deserialize the returned json string into an object and is also packaged into a promise. return (); }else{ return {} } }); promise = (function(data){ //Response content (data); }).catch(function(err){ (err); })
Notes:
- fetch() uses Promise and does not use callback functions, so it greatly simplifies the writing method and makes it simpler to write.
- fetch() adopts a modular design, and the API is scattered on multiple objects (Response object, Request object, Headers object), which is more reasonable; in contrast, the API design of XMLHttpRequest is not very good, and the input, output, and status are all managed on the same interface, making it easy to write very chaotic code.
- fetch() processes data through data streams (Stream objects) and can be read in chunks, which is conducive to improving website performance and reducing memory usage. It is very useful for requesting large files or slow network speeds. The XMLHTTPRequest object does not support data flow, all data must be placed in the cache, and does not support chunked reading. You must wait for all to be received and then spit it out again.
grammar:
fetch(url) .then(...) .catch(...)
For example: Get JSON data from the server
fetch('/users/ruanyf') // The response received by fetch() is a Stream object // () is an asynchronous operation that takes out all contents and converts them into JSON objects .then(response => ()) .then(json => (json)) .catch(err => ('Request Failed', err)); // equivalent to the following writing methodasync function getJSON() { let url = '/users/ruanyf'; try { let response = await fetch(url); return await (); } catch (error) { ('Request Failed', error); } } (getJSON()); // The obtained json data
Response object
Use Cases
export const winFetch = async ({ url, description, method, body, }: { url: string; description: string; method: string; body: { [key: string]: any }; }) => { (description, url, body); const res = await new Promise((resolve, reject) => { window .fetch(baseURL + url, { method, headers: { 'content-type': 'application/json' }, mode: 'cors', credentials: 'include', body: (body), }) .then((response) => response?.json().then( (json) => resolve(json), (err) => reject(err), ), ); }); return { data: res } as { data: { data: { [key: string]: any } } }; }; export async function delete(body: { id: number }) { const res = await winFetch({ url: '/aaa/bbb/delete/', description: 'Delete information', method: 'DELETE', body, }); return ; }
1. Synchronous properties
After the fetch() request is successful, the Response object is obtained. It corresponds to the HTTP response of the server.
The data contained in Response is read asynchronously through the Stream interface, but it also contains some synchronous properties corresponding to the headers of HTTP responses (Headers) that can be read immediately.
async function fetchText() { let response = await fetch('/users/ruanyf'); (); // 200 (); // } fetchText()
The header information attributes are as follows:
const response = await fetch(url);
1.: Return a boolean value indicating whether the request is successful
For example: true corresponds to the status codes of HTTP requests 200 to 299, false corresponds to other status codes.2. : Return a number representing the status code of the HTTP response
For example: 200, indicating a successful request3. The attribute returns a string representing the status information of the HTTP response
For example: After the request is successful, the server returns "OK"4. : Return the requested URL.
If: The URL exists a jump, the attribute returns the final URL.5.: Returns a boolean value indicating whether the request has been redirected.
6.: Returns the requested type. Possible values are as follows:
basic: Normal request, that is, a homologous request.
cors: Cross-domain request.
error: Network error, mainly used in Service Worker.
2. Judgment request
After fetch() makes a request, fetch() will report an error only when the network error or the connection is not possible. In other cases, the request will not be reported, but is considered to be successful.
Only by obtaining the true status code of the HTTP response through the attribute can we determine whether the request is successful.
async function fetchText() { let response = await fetch('/'); if ( >= 200 && < 300) { return await (); } else { throw new Error(); } }
Another way is to determine whether it is true
if () { // Request succeeded} else { // Request failed}
3. Operation header
The Response object also has a property that points to a Headers object, corresponding to all headers of the HTTP response.
The Headers object can be traversed using a for...of loop
const response = await fetch(url); for (let [key, value] of ) { (`${key} : ${value}`); } // orfor (let [key, value] of ()) { (`${key} : ${value}`); }
The following methods are provided to operate the header
Some of the following methods can modify the header because it inherits from the Headers interface. For HTTP responses, modifying headers is not very meaningful, and many headers are read-only and the browser does not allow modification.
The most commonly used one is ()
const response = await fetch(url); ():According to the specified key name,Return key value。 (): Return a boolean value,Indicates whether a header is included。 ():Set the specified key name to the new key value,If the key name does not exist, it will be added。 ():Add header。 ():Delete the header。 ():Return a traverser,You can traverse all key names in turn。 ():Return a traverser,You can traverse all key values in turn。 ():Return a traverser,You can traverse all key values in turn对([key, value])。 ():Iterate over the header in turn,Each header executes a parameter function。
4. Read content
The Response object provides different reading methods based on different types of data returned by the server.
The following 5 reading methods are all asynchronous, and the returned Promise objects are all returned. You must wait until the asynchronous operation is completed before you can get the complete data returned by the server.
const response = await fetch(url); ():Get text string,Used to obtain text data,for example HTML document。 ():get JSON Object。 ():get二进制 Blob Object,例如读取图片document,Show on the web page。 ():get FormData 表单Object,Mainly used in Service Worker in,Intercept user-submitted forms,After modifying certain data,Submit to the server。 ():get二进制 ArrayBuffer Object,主要用于获取流媒体document。
5. Create a copy
A Stream object can only be read once, and it will disappear after reading. This means that only one of the five read methods can be used, otherwise an error will be reported.
// Use() first and read the Stream.// If you call() later, there will be no content to read, so an error will be reported.let text = await (); let json = await (); // Report an error
The Response object provides a () method to create a copy of the Response object and implement multiple reads.
const response1 = await fetch(''); // () Copy a Response object and read the same image twiceconst response2 = (); const myBlob1 = await (); const myBlob2 = await (); = (myBlob1); = (myBlob2);
6. Underlying interface
The property is the underlying interface exposed by the Response object, and returns a ReadableStream object for user operation.
For example: used to read content in chunks and display the progress of download
const response = await fetch(''); // () method returns a traverserconst reader = (); while(true) { // The read() method of this traverser returns an object at a time, indicating the content block read this time const {done, value} = await (); // The done attribute is a boolean value, used to determine whether it has been read or not if (done) { break; } // The value attribute is an arrayBuffer array that represents the content of the content block, and the attribute is the size of the current block (`Received ${} bytes`) }
Customize HTTP requests
The first parameter of fetch() is the URL, and it can also accept the second parameter as a configuration object to customize the issued HTTP request
The HTTP request method, header, and data body are all set in this optionObj object.
fetch(url, optionObj)
The complete API of the second parameter of fetch() is as follows
The underlying layer of fetch() request uses the interface of the Request() object, and the parameters are exactly the same, so the above API is also the Request() API.
const response = fetch(url, { method: "GET", headers: { "Content-Type": "text/plain;charset=UTF-8" }, body: undefined, referrer: "about:client", referrerPolicy: "no-referrer-when-downgrade", mode: "cors", credentials: "same-origin", cache: "default", redirect: "follow", integrity: "", keepalive: false, signal: undefined });
Detailed explanation of parameters
method:HTTP Request method,POST、DELETE、PUTAll are set in this property。 headers:An object,Used to customize HTTP Requested header。 body:POST Requested data body。 cache:Specify how to handle cache。Possible values are as follows: /* default: default value, first look for matching requests in the cache. no-store: directly requests the remote server and does not update the cache. reload: directly request the remote server and update the cache. no-cache: Compare the server resources with the local cache. Only if there is a new version, use the server resources, otherwise use the cache. force-cache: Cache is preferred. Only if there is no cache, the remote server will be requested. only-if-cached: Only check the cache. If it does not exist in the cache, it will return a 504 error. */ mode: Specify the requested mode。Possible values are as follows: /* cors: default value, allows cross-domain requests. same-origin: Only same-origin requests are allowed. no-cors: The request method is limited to GET, POST, and HEAD, and can only use a few simple headers. It cannot add complex headers across domains, which is equivalent to the request that can be made when submitting a form. */ credentials:Specify whether to send Cookie。Possible values are as follows: /* same-origin: Default value, send cookies when requesting same origin, and not sending when requesting across domains. include: Cookies are sent regardless of homologous requests or cross-domain requests. omit: No sending. */ signal:Specify one AbortSignal Example,Used to cancelfetch()ask keepalive:Used for page uninstallation,Tell the browser to keep connected in the background,Continue to send data。 /* A typical scenario is that when a user leaves the web page, the script submits some statistics on user behavior to the server. At this time, if the keepalive attribute is not used, the data may not be sent because the browser has uninstalled the page. */ redirect: Specify HTTP How to handle jump。Possible values are as follows: /* Follow: Default value, fetch() jumps with HTTP. error: If a jump occurs, fetch() will report an error. manual: fetch() does not follow HTTP redirection, but the property will point to a new URL, and the property will become true. The developer will decide how to handle the redirection in the future. */ integrity:Specify one哈希值,Used for inspection HTTP Is the data sent back equal to this preset hash value?。 /* For example, when downloading a file, check whether the SHA-256 hash value of the file matches and ensures that it has not been tampered with. fetch('/file', { integrity: 'sha256-abcdef' }); */ referrer: For settingfetchask的refererHeader。 /* This property can be any string or set to an empty string (that is, no referer header is sent). */ referrerPolicy: For settingRefererHeader的规则。Possible values are as follows: /* no-referrer-when-downgrade: Default value, always sends the Referer header unless it is not sent when requesting HTTP resources from the HTTPS page. no-referrer: Do not send Referer header. origin: The Referer header only contains the domain name and does not contain the complete path. origin-when-cross-origin: The same-origin request Referer header contains the complete path, and cross-domain requests only contain the domain name. same-origin: Cross-domain requests do not send Referer, same-origin requests are sent. strict-origin: The Referer header only contains domain names. The Referer header is not sent when the HTTPS page requests HTTP resources. strict-origin-when-cross-origin: The Referer header contains the full path when requesting the same origin, and only the domain name is included when requesting the HTTP resource. This header is not sent when requesting HTTP resources on the HTTPS page. unsafe-url: Regardless of the situation, the Referer header is always sent. */
Cancel fetch request
After the fetch() request is sent, if you want to cancel the request in the middle, you need to use the AbortController object
let controller = new AbortController(); fetch(url, { signal: }); ('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: Automatically cancel the request after 1 second
let controller = new AbortController(); setTimeout(() => (), 1000); try { let response = await fetch('/long-operation', { signal: }); } catch(err) { if ( == 'AbortError') { ('Aborted!'); } else { throw err; } }
Summarize
This is the article about the usage of fetch() in JavaScript. For more information about JS fetch(), please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!