当前位置:网站首页>Fetch request details
Fetch request details
2022-06-23 03:23:00 【weichushun】
fetch yes XMLHttpRequest Upgraded version , Use js The script makes a network request , But with the XMLHttpRequest The difference is ,fetch Way to use Promise, comparison XMLHttpRequest More concise . So we say goodbye XMLHttpRequest, introduce fetch How to use ?
One 、fetch Introduce
fetch() Is a global method , Provide a simple , Get resources across the network in a reasonable way . Its request is based on Promise Of , Need detailed study Promise , Please click on 《 Promise Detailed explanation 》. It is designed to replace the traditional xhr Born .
1.1、fetch Use the syntax
fetch(url,options).then((response)=>{
// Handle http Respond to
},(error)=>{
// Handling errors
})url : Is the address to send the network request .
options: Send request parameters ,
- body - http Request parameters
- mode - Specify the request mode . The default value is cros: Allow cross-domain ;same-origin: Only homologous requests are allowed ;no-cros: Limited to get、post and head, And only a few simple headers can be used .
- cache - User specified cache .
- method - Request method , Default GET
- signal - For cancellation fetch
- headers - http Request header Settings
- keepalive - For page unloading , Tell the browser to stay connected in the background , Continue sending data .
- credentials - cookie Set up , Default omit, Ignore without cookie,same-origin Homologous request band cookie,inclue Both cross domain and homology will bring cookie.
1.2、response object
fetch After the request is successful , Respond to response The object is as shown in the figure :

- status - http Status code , The scope is 100-599 Between
- statusText - Server return status text description
- ok - Returns a Boolean value , If the status code 2 At the beginning , be true, conversely false
- headers - Response head
- body - Response body . In response to the data in the body , Handle according to the type .
- type - Return request type .
- redirected - Returns a Boolean value , Indicates whether a jump has occurred .
1.3、 How to read content
response Object according to different types of data returned by the server , Different reading methods are provided . There were :
- response.text() -- Get the text string
- response.json() - obtain json object
- response.blob() - Get binary blob object
- response.formData() - obtain fromData Form object
- response.arrayBuffer() - Get binary arrayBuffer object
Above 5 A way , All of them promise object , Wait until the asynchronous operation has to end , To get the complete data returned by the server .
1.4、response.clone()
stream Object can only be read once , After reading, it's gone , It means , The five reading methods above , You can only use one , Otherwise, an error will be reported .
therefore response The object provides clone() Method , establish respons Object copy , Achieve multiple reads . as follows : Put a picture , Read twice :
const response1 = await fetch('flowers.jpg');
const response2 = response1.clone();
const myBlob1 = await response1.blob();
const myBlob2 = await response2.blob();
image1.src = URL.createObjectURL(myBlob1);
image2.src = URL.createObjectURL(myBlob2);1.5、response.body()
body Property returns a ReadableStream object , For user operation , It can be used to read content in blocks , Displaying the progress of the download is one of the applications .
const response = await fetch('flower.jpg');
const reader = response.body.getReader();
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
console.log(`Received ${value.length} bytes`)
}response.body.getReader() Returns a traverser , This traverser read() Method returns an object each time , Represents the content block read this time .
Two 、 When asked POST and GET Deal with... Separately
The request method is different , Value transfer methods are also different .xhr Will deal with separately get and post The data transfer , And request header settings , Again fetch It also needs to be handled separately .
2.1、get The way
Only need url Add transmission data ,options Add the request method in . As shown in the following code :
<input type="text" id="user"><br>
<input type="password" id="pas"><br>
<button οnclick="login()"> Submit </button>
<script>
function login(){
fetch(`http://localhost:80/fetch.html?user=${user.value}&pas=${pas.value}`,{
method:'GET'
}).then(response=>{
console.log(' Respond to ',response)
})
}
</script>2.2、post The way
Use post When sending a request , Need to set request header 、 Request data, etc .
The previous instance , Rewrite into post How to submit data , The code is as follows :
fetch(`http://localhost:80/ES6 Exercises /53fetch.html`,{
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
},
body:`user=${user.value}&pas=${pas.value}`
}).then(response=>{
console.log(' Respond to ',response)
})If it is submitted json Data time , Need to put json Convert to string . Such as
body:JSON.stringify(json)
If you submit form data , Use formData Under transformation , Such as :
body:new FormData(form)
Upload files , It can be included in the whole form and submitted together , Such as :
const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');
fetch('/avatars', {
method: 'POST',
body: data
});Upload binary data , take bolb or arrayBuffer Data placement body In the attribute , Such as :
let blob = await new Promise(resolve =>
canvasElem.toBlob(resolve, 'image/png')
);
let response = await fetch('/article/fetch/post/image', {
method: 'POST',
body: blob
});3、 ... and 、fetch Common pit
3.1、fetch Compatibility
fetch The native support rate is shown in the figure :

fetch It's a relatively new technology ,IE Browser does not support , There are other lower versions of browsers that do not support , So if you use fetch when , Browser compatibility needs to be considered .
terms of settlement : introduce polyfill Perfect support IE8 above .
- because IE8 yes ES3, Need to introduce ES5 Of polyfill: es5-shim, es5-sham
- introduce Promise Of polyfill:es6-promise
- introduce fetch Detection Library :fetch-detector
- introduce fetch Of polyfill: fetch-ie8
- Optional : If you still use jsonp, introduce fetch-jsonp
- Optional : Turn on Babel Of runtime Pattern , Use now async/await
polyfill The principle is to detect fetch Do you support , If not, use xhr Realization . Support fetch Browser , Response Chinese will be garbled , So use fetch-detector and fetch-ie8 Solve the mess .
3.2、fetch Default without cookie
Pass on cookie when , Must be in header Add... To the parameter credentials:'include', Just like xhr Will the current cookie With request .
3.3、 exception handling
fetch differ xhr ,xhr Bring your own cancel 、 Error and other methods , So the server returns 4xx or 5xx when , You won't throw an error , Need to be handled manually , adopt response Medium status Field to determine .
classification : Front end knowledge sharing
边栏推荐
- If there is a smart bus visualization platform, can "beginning" restart indefinitely?
- Initial xxE
- [Alibaba middleware technology series] "Nacos technology" service registration and discovery related principle analysis
- Encryption related to returnee of national market supervision public service platform
- Simply use the pagoda to build WordPress
- JS counts the number of times a string appears in another string
- JS to determine whether the page is opened for the first time today
- Construction and exploration of vivo database and storage platform
- Drill down into handler, looper, messagequeue
- Win11 client remote ECS black screen
猜你喜欢

Analysis on the development of China's graphene industry chain in 2021: with the support of energy conservation and environmental protection policies, the scale of graphene industry will continue to e
![[quick view] Analysis on the development status and future development trend of the global and Chinese diamond cultivation industry in 2021 [figure]](/img/f1/972a760459a6d599b5681aa634df09.jpg)
[quick view] Analysis on the development status and future development trend of the global and Chinese diamond cultivation industry in 2021 [figure]
![Analysis on demand and market scale of China's steamed stuffed bun industry in 2020 [figure]](/img/4b/dd272f98b89a157180bf68570d2763.jpg)
Analysis on demand and market scale of China's steamed stuffed bun industry in 2020 [figure]

Encryption related to returnee of national market supervision public service platform

Analysis on the development of duty-free industry in Hainan Province in 2021: the implementation of the new policy makes the duty-free market in Hainan more "prosperous" [figure]
![Analysis on the development prospect of China's brain computer interface industry in 2021: wide application prospect, sustained and rapid growth of market scale [figure]](/img/84/192d152ceb760264b6b555b321f129.jpg)
Analysis on the development prospect of China's brain computer interface industry in 2021: wide application prospect, sustained and rapid growth of market scale [figure]

Analysis on the development of China's satellite navigation industry chain in 2021: satellite navigation is fully integrated into production and life, and the satellite navigation industry is also boo
![Analysis on development history, industrial chain, output and enterprise layout of medical polypropylene in China in 2020 [figure]](/img/28/ebfc25ec288627706e15a07e6bdb77.jpg)
Analysis on development history, industrial chain, output and enterprise layout of medical polypropylene in China in 2020 [figure]
![Analysis of China's integrated circuit industry chain in 2021: huge downstream market demand [figure]](/img/de/d73805aaf4345ca3d2a7baf85aab8d.jpg)
Analysis of China's integrated circuit industry chain in 2021: huge downstream market demand [figure]
![Analysis on the development status of China's watch industry in 2021: a large number of electric watches are imported [figure]](/img/ca/672bfe49c8123da8679b2abeb43a2e.jpg)
Analysis on the development status of China's watch industry in 2021: a large number of electric watches are imported [figure]
随机推荐
WPF developer essential control library newbeecoder UI —NbMessageBox
Initialize MySQL Gorm through yaml file
The difference between the use of return, break and continue in the if statement in JS
2D visual empowerment smart water green intensive development
How to configure the domain name with low code of micro build
Wi Fi 6 is coming - larger capacity, lower latency, faster network speed and more security
CFS topics
Network security memorabilia - Summary of vulnerability exploitation events in 2021
Downloading sqlserver versions (2016-2019)
DAAS architecture and Implementation (I)
Easygbs service is killed because the user redis is infected with the mining virus process. How to solve and prevent it?
Wwdc21 - App store server API practice summary
JS how to delete an item specified in an array
Learning records - things inherited by subclass parent of C #
Implementing StdevP function of Excel with PHP
Flowable refactoring process editor to obtain user information
Use ES6 new Target to simulate abstract classes
Cve-2021-4034 reappearance
Use micro build to realize search function
To implement a task scheduling system, it is enough to read this article