Data request method Fetch

I. Introduction

In the front-end and back-end separation projects, it has become a routine operation for the front-end to request the back-end interface to obtain the back-end data, complete the rendering of the page content or judge the functional status. So, what are the main ways for the front end to request the back end interface to obtain and parse data:

  1. Refresh the page: the most direct but the worst way to experience
  2. form form: it will trigger page jump, and repeated requests in the page cannot be realized
  3. iream: comparatively consumes performance, and the control cost is too high
  4. Ajax - Use the XMLHttpRequest object to make asynchronous requests, which greatly improves the user experience and realizes in-page requests
  5. Fetch - a substitute for Ajax, a browser built-in method, encapsulates the Promise mechanism, and optimizes the asynchronous problem
  6. jQuery - a front-end framework that encapsulates the data request module, but the size is large
  7. Many third-party open source libraries such as axios and request: the secondary packaging of native methods has its own advantages and disadvantages, and a hundred schools of thought contend

This article mainly introduces the browser's built-in request method fecth.

2. About Fetch API

  1. Fetch is a browser built-in API. In the browser environment, it can be windowobtained through the top-level object.
  2. Fetch provides common definitions for Requestand Response(and other network request-related) objects. It shows that the target of Fetch is not only the browser environment, it is also possible to provide support for Fetch in the server environment in the future.
  3. When using Fetch to send requests or obtain resources, you need to use fetch()the method.
  4. fetch()The method must accept one parameter: the path to request, and an optional parameter Requestobject. Whether the request was successful or not, it returns a Promiseobject
    • When the request is successful, the requested Responseobject will be obtained
    • When the request fails, you get aTypeError
    • It should be noted that when receiving an HTTP status code representing an error (such as 404), the fetch()returned from Promisewill not be marked as reject, only when the network failure or the request is blocked, it will be marked as reject. But fetch will modify the attribute resolveof the return value okas false.

3. Basic use of the fetch() method

// 请求成功,resolve
const url = "https://gitee.com/api/v5/users/liyangyf";
fetch(url).then( response=>console.log(response) )	// 此时resolve得到的是response对象

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-vrvKGxiQ-1663557491089)(./image-1.png)]

// 请求成功,resolve,但后端返回404
const url = "https://gitee.com/api/v5/users/liyangyf-test";
fetch(url).then( response=>console.log(response) )

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-row1nrqs-1663557491092)(./image-2.png)]

It should be noted that what is obtained at this time is only Responsethe object. If you need to further obtain interface data, you must further parse Responsethe object.

const url = "https://gitee.com/api/v5/users/liyangyf";
fetch(url).then( response=>response.json() )		// 将response数据解析成json
					.then( json=>console.log(json) )

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-eM1Ian6a-1663557491093)(./image-3.png)]

1. ResponseAnalysis of common synchronization attributes of objects:

  1. `Response.ok`:布尔值,表示请求是否成功。`true`对应 HTTP 请求的状态码 200 到 299,`false`对应其他状态码。
  2. `Response.status`:数值,表示 HTTP 回应的状态码(如200,表示成功请求)
  3. `Response.statusText`:字符串,表示 HTTP 回应的状态信息(如请求成功后,服务器返回"OK")
  4. `Response.url`:请求的 URL。如果 URL 存在跳转,该属性返回的是最终 URL。
  5. `Response.type`:请求的类型。可能的值:
   1. `basic`:普通请求,即同源请求
   2. `cors`:跨域请求
   3. `error`:网络错误
   4. `opaque`:如果`fetch()`请求的`type`属性设为`no-cors`,就会返回这个值,详见请求部分。表示发出的是简单的跨域请求,类似`form`表单的那种跨域请求。
   5. `opaqueredirect`:如果`fetch()`请求的`redirect`属性设为`manual`,就会返回这个值,详见请求部分。
  6. `Response.redirected`属性返回一个布尔值,表示请求是否发生过跳转。

2. ResponseAnalysis of the method of reading the content of the object:

  1. response.text(): Get a text string, such as html data.
  2. response.json(): get JSON object.
  3. response.blob(): Get a binary Blob object.
  4. response.formData(): Get FormData form object.
  5. response.arrayBuffer(): Get binary ArrayBuffer objects, such as streaming media files, video and audio classes

4. Requests with parameters

  1. The get method carries parameters:

The Fetch API stipulates that when transferring data in the GET method, the data cannot be sent directly through the request parameters options, and the data can only be spliced ​​​​to the url for sending.

let url = "http://icodeilife.club:3000/api/pro/search";

// 准备要发送的数据
const query = {
    
    
  sKey:"小米10pro"
}

// 将数据拼接到url
url += "?" + queryParse(query);

// 配置请求参数
const options = {
    
    method: "GET"}
fetch(url, options).then(res=>res.json()).then(json=>{
    
    
		console.log(json)
})

// 解析query数据
function queryParse(query){
    
    
    let queryText = "";
    for(let key in query){
    
    
        queryText += `${
      
      key}=${
      
      query[key]}&`;
		}
    return queryText.slice(0,-1);
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Dd4Vajko-1663557491094)(./image-4.png)]

  1. The post method carries parameters

Relatively speaking, it is much more convenient to send data in POST mode, which can optionsbe configured directly in , but you need to pay attention to setting the properties headersof the object Content-typeasapplication/x-www-form-urlencoded; charset=UTF-8

let url = "http://icodeilife.club:3000/api/user/register";

// 准备要发送的数据
const query = {
    
    
  	username: "杨树林",
  	password: "123456",
  	tel: 17612345678,
  	code: 6666
}

// 配置请求参数
const options = {
    
    
  	method: 'POST',
  	headers: {
    
    
    	"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
  	},
  	body: queryParse(query)
}

fetch(url, options).then(res=>res.json()).then(json=>{
    
    
  	console.log(json);
})

// 解析query数据
function queryParse(query){
    
    
    let queryText = "";
    for(let key in query){
    
    
        queryText += `${
      
      key}=${
      
      query[key]}&`;
		}
    return queryText.slice(0,-1);
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Zl2sgTyz-1663557491095)(./image-5.png)]

  1. The full configuration properties on fetch()the second parameter of the method areoptions
const options = {
    
    
  method: "POST",
  headers: {
    
    
    "Content-Type": "text/plain;charset=UTF-8"
  },
  body: "key1=value1&key2=value2",
  referrer: "about:client",
  referrerPolicy: "no-referrer-when-downgrade",
  mode: "cors", 
  credentials: "same-origin",
  cache: "default",
  redirect: "follow",
  integrity: "",
  keepalive: false,
  signal: undefined
};

fetch()The bottom layer of the request uses the interface of the Request() object , and the parameters are exactly the same, so optionsthe configurations of and Request()the configurations of are the same.

in:

method: HTTP request method, POST, DELETE, PUTare all set in this attribute.

headers: An object used to customize the headers of the HTTP request.

body: The data body of the POST request.

cache: Specifies how to handle caching.

  1. default: Default value, read cache first; no-store: Request server, do not update cache;

    1. reload: Request the server to update the cache;
    2. no-cache: Compare the server resource with the local cache, if there is a new version use the server resource, otherwise use the cache;
    3. force-cache: Cache priority, only when there is no cache, the remote server is requested;
    4. only-if-cached: Only check the cache, if it does not exist in the cache, a 504 error will be returned.

mode: Specifies the mode of the request.

  1. cors: default value, allowing cross-domain requests;

    1. same-origin: Only same-origin requests are allowed;
    2. no-cors: The request method is limited to GET, POST and HEAD, which is equivalent to the request that can be sent by submitting a form.

credentials: Whether to send cookies.

  1. same-origin: Default value, send when same-origin request, not send when cross-domain request;
  2. include:send;
  3. omit:Do not send.

signal: Specifies an AbortSignal instance for canceling fetch()the request. See next section↓↓↓

keepalive: Boolean value, when the page is unloaded, tell the browser to keep the connection in the background and continue to send data.

redirect: The processing method of HTTP jump.

  1. follow: default value, fetch()follow the HTTP jump;
  2. error: If a jump occurs, fetch()an error will be reported;
  3. manual: fetch()Does not follow the HTTP jump, but response.urlthe attribute will point to the new URL, and response.redirectedthe attribute will become true, and it is up to the developer to decide how to handle the jump later.

integrity: Specifies a hash value, which is used to check whether the data returned by the HTTP response is equal to the preset hash value.

  • For example, when downloading a file, check that the SHA-256 hash of the file matches to ensure that it has not been tampered with.

referrer: Used to set the headers fetch()of the request .referer

referrerPolicy: Specifies refererthe rule for the HTTP header field

  1. no-referrer-when-downgradeReferer: default value, headers are always sent , unless not sent when requesting HTTP resources from HTTPS pages;
  2. no-referrer: do not send Refererheaders;
  3. origin: RefererThe header only contains the domain name, not the full path;
  4. origin-when-cross-origin: The same-origin request Refererheader contains the complete path, and the cross-origin request only contains the domain name;
  5. same-origin: Cross-domain requests are not sent Referer, same-origin requests are sent;
  6. strict-origin: RefererThe header only contains the domain name, and the HTTPS page does not send Refererthe header when requesting HTTP resources;
  7. strict-origin-when-cross-originReferer: The header contains the full path for same-origin requests , only the domain name is included for cross-domain requests, and this header is not sent when HTTPS pages request HTTP resources;
  8. unsafe-urlReferer: headers are always sent no matter what

5. Termination fetch()request

fetch()After the request is sent, if it has not been completed for a long time, AbortControllerthe object can be used to terminate the request early.

// 创建 AbortController 实例
let controller = new AbortController();
let signal = controller.signal;

// 配置对象的signal属性必须指定接收 AbortController 实例发送的信号controller.signal
fetch(url, {
     
     
signal: signal
});

// 监听取消事件
signal.addEventListener('abort',() => console.log('abort!'));

// 发出取消信号
controller.abort();

// 查看取消信号是否已经发出
console.log(signal.aborted); // true

Handling of request timeout

let controller = new AbortController();
setTimeout(() => controller.abort(), 1000);

try {
     
     
let response = await fetch('/long-operation', {
     
     
 signal: controller.signal
});
} catch(err) {
     
     
if (err.name == 'AbortError') {
     
     
 console.log('Aborted!');
} else {
     
     
 throw err;
}
}

that's all

For an in-depth look, refer to the Fatch API .

Guess you like

Origin blog.csdn.net/weixin_41636483/article/details/126930212