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:
- Refresh the page: the most direct but the worst way to experience
- form form: it will trigger page jump, and repeated requests in the page cannot be realized
- iream: comparatively consumes performance, and the control cost is too high
- Ajax - Use the XMLHttpRequest object to make asynchronous requests, which greatly improves the user experience and realizes in-page requests
- Fetch - a substitute for Ajax, a browser built-in method, encapsulates the Promise mechanism, and optimizes the asynchronous problem
- jQuery - a front-end framework that encapsulates the data request module, but the size is large
- 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
- Fetch is a browser built-in API. In the browser environment, it can be
window
obtained through the top-level object. - Fetch provides common definitions for
Request
andResponse
(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. - When using Fetch to send requests or obtain resources, you need to use
fetch()
the method. fetch()
The method must accept one parameter: the path to request, and an optional parameterRequest
object. Whether the request was successful or not, it returns aPromise
object- When the request is successful, the requested
Response
object will be obtained - When the request fails, you get a
TypeError
- It should be noted that when receiving an HTTP status code representing an error (such as 404), the
fetch()
returned fromPromise
will not be marked asreject
, only when the network failure or the request is blocked, it will be marked asreject
. But fetch will modify the attributeresolve
of the return valueok
asfalse
.
- When the request is successful, the requested
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 Response
the object. If you need to further obtain interface data, you must further parse Response
the 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.
Response
Analysis 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.
Response
Analysis of the method of reading the content of the object:
response.text()
: Get a text string, such as html data.response.json()
: get JSON object.response.blob()
: Get a binary Blob object.response.formData()
: Get FormData form object.response.arrayBuffer()
: Get binary ArrayBuffer objects, such as streaming media files, video and audio classes
4. Requests with parameters
- 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)]
- The post method carries parameters
Relatively speaking, it is much more convenient to send data in POST mode, which can
options
be configured directly in , but you need to pay attention to setting the propertiesheaders
of the objectContent-type
asapplication/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)]
- 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, sooptions
the configurations of andRequest()
the configurations of are the same.in:
method
: HTTP request method,POST
,DELETE
,PUT
are 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.
default
: Default value, read cache first;no-store
: Request server, do not update cache;
reload
: Request the server to update the cache;no-cache
: Compare the server resource with the local cache, if there is a new version use the server resource, otherwise use the cache;force-cache
: Cache priority, only when there is no cache, the remote server is requested;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.
cors
: default value, allowing cross-domain requests;
same-origin
: Only same-origin requests are allowed;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.
same-origin
: Default value, send when same-origin request, not send when cross-domain request;include
:send;omit
:Do not send.
signal
: Specifies an AbortSignal instance for cancelingfetch()
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.
follow
: default value,fetch()
follow the HTTP jump;error
: If a jump occurs,fetch()
an error will be reported;manual
:fetch()
Does not follow the HTTP jump, butresponse.url
the attribute will point to the new URL, andresponse.redirected
the attribute will becometrue
, 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 headersfetch()
of the request .referer
referrerPolicy
: Specifiesreferer
the rule for the HTTP header field
no-referrer-when-downgrade
Referer
: default value, headers are always sent , unless not sent when requesting HTTP resources from HTTPS pages;no-referrer
: do not sendReferer
headers;origin
:Referer
The header only contains the domain name, not the full path;origin-when-cross-origin
: The same-origin requestReferer
header contains the complete path, and the cross-origin request only contains the domain name;same-origin
: Cross-domain requests are not sentReferer
, same-origin requests are sent;strict-origin
:Referer
The header only contains the domain name, and the HTTPS page does not sendReferer
the header when requesting HTTP resources;strict-origin-when-cross-origin
Referer
: 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;unsafe-url
Referer
: 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, AbortController
the 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 .