当前位置:网站首页>About the foundation of fetch
About the foundation of fetch
2022-07-25 23:25:00 【Plant a tree】
There may be some very old programs still in use XHR, Similar to the following :
const request = new XMLHttpRequest()
request.responseType = 'json'
request.open('GET', '/url', true)
request.onload = () => {
console.log(request.response)
}
request.onerror = () => {
console.log('shits happen!')
}
request.send(null)
This way, use XHR Asynchronous access 、 Reading resources is cumbersome , Phase comparison Fetch() Allows you to create similar XHR Of network visit , But it is simpler and cleaner to use API, You don't need to call back many times and remember XHR complex API.Fetch API The bottom is through Promises Realization .
XMLHttpRequest
A relatively complete XMLHttpRequest At least two events need to be monitored (onload、onerror) To achieve successful and failed callbacks , And call open() and send()
function reqListener() {
var data = JSON.parse(this.responseText);
console.log(data);
}
function reqError(err) {
console.log('Fetch Error :-S', err);
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', './api/some.json', true);
oReq.send();
Fetch
A simple Fetch Examples are as follows :
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
Fetch The syntax of is more semantic 、 It's easy to understand . In the above example, we first judge response Of status code , If it is 200 We're going to response It can be interpreted as JSON
fetch() Requested returned response yes Stream object , So we call response.json Because the stream object is read asynchronously, the return is a Promise object .
Fetch use async Optimize the code
because Fetch The bottom layer is made of Promise Realization , We can use it directly async To optimize the above code , Reduce callback , Make it more semantic 、 Easy to understand
async function geturl(){
try{
let res = await fetch('./api/some.json')
if(res.status == 200){
console.log(await res.text())
}
} catch(err){
console.log(err)
}
}
Response Metadata
In the example above , We get it Response Object's status Status and how to response Object to JSON object , Let's see Response Other metadata of the object :
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
Response type
When we launch a Fetch When asked , Back to response The response will come with a response.type attribute (basic、cors、opaque).response.type Attribute describes the source of the asynchronous resource , At the same time, there are corresponding treatment methods .
When we initiate a homologous request ,response.type by basic, And you can start from response Read all the information .
If we visit a non homologous domain name , And return the corresponding CORs Response header time , Then the request type is cors.cors and basic Very similar , Except cors You cannot access in the response Cache-Control,Content-Language,Content-Type,Expires,Last-Modified and Pragma
When we request a domain name from a different source , If the returned response header does not CORS Information , So this response The corresponding type is opaque type . One opaque The response is unable to read the returned data 、 state , It's not even certain whether the request was successful .
We can customize it Fetch The pattern of the request , Request to return the corresponding type of response , There are several responses :
- same-origin Only the same source request is returned , Other types will be reject
- cors Receive homology 、 Non homologous requests , Return yes CORs The response of the head
- cors-with-forced-preflight A security check will be done before sending the request
- no-cors Used to initiate No CORS Header and non homologous request , And will return to opaque Respond to . But at present, this type can only be used in Service Worker Use in , stay window.fetch You can't use
fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});
Commitment chain
because Fetch Back to response Is based on Promise Realization , So we can put a few like a chain Promise Connect them in series , As shown below :
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
Yes, of course , We can also use async Code optimization
async function geturl(url){
try {
let res = await fetch(url)
if(res.status >= 200 && res.status < 300){
console.log('Request succeeded with JSON response', await res.json())
}
}catch (err){
console.log(err)
}
}
geturl('users.json')
Post request
When we use Fetch launch Post When asked , Manual setting required method Parameters and body Parameters , as follows :
fetch(url, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'foo=bar&lorem=ipsum'
})
.then(json)
.then(function (data) {
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
console.log('Request failed', error);
});
If not explicitly specified method Parameters , So default Get request
belt Cookie Send a request
If we want to bring cookie Parameters , Then you need to explicitly specify credentials Parameters :
fetch(url, {
credentials: 'include'
})边栏推荐
- Source code of YY music wechat applet imitating Netease cloud music
- PHP JSON variable array problem
- Why are there many snapshot tables in the BI system?
- Take root downward, grow upward, and explore the "root" power of Huawei cloud AI
- Serialize data type
- 策略模式_
- Serialize addition, deletion, modification and query
- 谷粒学苑P98踩坑 e.GlobalExceptionHandler : null
- 学习探索-3d轮播卡片
- 1913. 两个数对之间的最大乘积差-无需排序法
猜你喜欢

@Import

Secure code warrior learning record (III)

File contains vulnerability

Tencent map API request source is not authorized, this request source domain name

Cuteone: a onedrive multi network disk mounting program / with member / synchronization and other functions
![[interface performance optimization] reasons for index failure and how to optimize SQL](/img/b9/64058c823c4497ac36bfb62a101816.jpg)
[interface performance optimization] reasons for index failure and how to optimize SQL

Firewall command simple operation

Source code of YY music wechat applet imitating Netease cloud music

npm+模块加载机制

WebMvcConfigurationSupport
随机推荐
CTS test method "suggestions collection"
Serialize operator
新手哪个券商开户最好 开户最安全
Enterprise level inventory management system of code audit
【微信小程序】页面导航
js正则表达式匹配ip地址(ip地址正则表达式验证)
The VM session was closed before any attempt to power it on
Source code of wechat applet for discerning flowers and plants / source code of wechat applet for discerning plants
Npm+ module loading mechanism
How does Navicat modify the language (Chinese or English)?
Classes and objects (3)
Expression of directional signal -- complex exponential signal
Multimodal deep multi modal sets
Wechat official account, wechat payment development
[QNX hypervisor 2.2 user manual]9.7 generate
Dynamic memory management
POI special effects Market Research
Strategy mode_
关于优先队列
TS class