编程知识 cdmana.com

Front and back end data interaction (IV) -- detailed explanation of fetch request

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 :

  1. response.text() -- Get the text string
  2. response.json() - obtain json object
  3. response.blob() - Get binary blob object
  4. response.formData() - obtain fromData Form object
  5. 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 onclick="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 .

Link to the original text : https://www.cnblogs.com/web-learn/p/15236710.html

版权声明
本文为[stupid]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145421686E.html

Scroll to Top