FetchAPI is not just a fetch method for making network requests, it provides generic definitions of objects
Request
andResponse
(and other network request-related) objects. These definitions replace some of the more scattered definitions in the previous one. In a word, In short, web requests are gradually standardized.
A simple use case for FetchAPI:
fetch(`url`,{
method:'get',
headers:{},
body:JSON.stringify({
name:'Andy'
})
}).then(response => {
return response.json()
}).then(res => {
console.log('结果在这里--->',res)
})
复制代码
The above code only deals with the JSON
data returned by the server, and does not consider other types of response data: if the server returns a file, the above code will fail: Uncaught SyntaxError: Unexpected end of JSON input
.
I myself have little understanding and use of FetchAPI, and an error similar to the above caught my attention, so I took the time to check the information and realized its revolutionary significance: standardizing web requests .
FetchAPI makes network requests more standardized
First, FetchAPI defines several main interfaces at the language level:
Request
Indicates a network requestResponse
Data representing a network requestHeaders
A series of operations that define request headers and response headers
A network request can be represented by the following process:
//创建请求request
//1.构造请求头
const headers = new Headers()
headers.append('content-type','application/json')
//2.构造request
const request = new Request('url',{
method:'get',
mode:'cors',//表示一次跨资源共享的请求
headers:headers,
//...
})
//发送
fetch(request).then(response => {
if(response.ok){
//一次ok的响应:200
}else{
//其他的响应: 4xx, 5xx
}
const contentType = response.headers.get('content-type')
//根据内容类型调用不同的方法 .blob(), .text(), .formData()
if(contentType === 'application/json'){
return response.json()
}else{
//...
}
},err=>{
//没有收到响应
/*
1. 网络故障导致发送失败
2. 超时
*/
}).then(res => {
console.log('结果在这里--->',res)
})
复制代码
Above, we specified the request-related modules through the constructor:
- request
- headers
- response
Then Response
the interface provides ok
Boolean properties to determine the validity of the response. In addition, you can specify whether the request mode is a cross-domain request or a same-origin request ( mode
), and specify whether to carry credentials ( credentials
). Everything becomes configurable, which XMLHttpRequest
is much more elegant than the processing method here.
In addition, we can also construct custom response
: const res = new Response()
.
All the APIs used above belong to FetchAPI
.
How to handle redirects
As we all know, there is no concept of redirection in Ajax, because it belongs to the asynchronous update of the layout of the document, and cannot directly redirect the page to a certain path like a traditional response.
If the front end wants to introduce redirection in Ajax, it can only return some agreed data through the server (usually put HttpHeader
it as a mark), and js reads the header for page navigation in the client.
FetchAPI
Taking this into account, normalize it:
//服务端
...
//一个API接口的controller片段
res.status(302).redirect('/love')
...
//客户端
fetch(request).then(response => {
//response.redirected 表示该响应是否是重定向的
const isRedirected = response.redirected
const redirectedUrl = response.url
//客户端判定是否跳转
})
复制代码
Here we don't need any additional data conventions on the front and back ends, the specification is much simpler, isn't it?
How to handle timeout issues
It should be pointed out here that FetchAPI does not provide timeout
a definition, but instead gives control to development. Although it reduces some convenience, it improves the robustness of the interface in the long run.
We can AbortController
handle the timeout of the fetch request through the interface
const abortController = new AbortController()
//10秒钟后终止关联的请求(超时间隔为10s)
setTimeout(()=>{
abortController.abort()
},10000)
fetch('/api/login', {
method: 'get',
signal:abortController.signal
}).then(res => {
},err=>{
console.log(`这里可以捕获到超时错误-->`,err)
})
复制代码
Summarize
FetchAPI essentially summarizes, summarizes, splits, and refines some of the scattered methods on Ajax before into individual modules. These modules complement each other and combine to support the architecture of web requests. And each module provides many convenient operation methods.
If you haven't used FetchAPI much, I suggest you try it.