当前位置:网站首页>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'
})边栏推荐
- How does Navicat modify the language (Chinese or English)?
- Thinkphp6 temporarily close the layout
- Scaffold installation
- 推荐系统——An Embedding Learning Framework for Numerical Features in CTR Prediction
- Implementation of mesh parameterized least squares conformal maps (3D mesh mapping to 2D plane)
- 加拿大EE通道
- Tencent map API request source is not authorized, this request source domain name
- Serialize data type
- Duplicate numbers in array
- 策略模式_
猜你喜欢

Custom MVC principle

WordPress removes the website publishing time

Dynamic memory management

serialization and deserialization

类和对象(2)(6个默认成员函数)

Tips for using (1)

Expression of directional signal -- complex exponential signal

自定义mvc原理

What has Amazon cloud technology done right to become the leader of cloud AI services for three consecutive years?

Npm+ module loading mechanism
随机推荐
Cuteone: a onedrive multi network disk mounting program / with member / synchronization and other functions
[code case] blog page design (with complete source code)
Mongodb query and projection operators
Drive board network cable directly connected to computer shared network configuration
类和对象(2)(6个默认成员函数)
[wechat applet] page navigation
chown: changing ownership of ‘/var/lib/mysql/‘: Operation not permitted
E-commerce RPA, a magic weapon to promote easy entry
WordPress removes the website publishing time
@Import
1913. 两个数对之间的最大乘积差-无需排序法
新手哪个券商开户最好 开户最安全
JS get the current date and time
PyTorch的数据输入格式要求及转换
Duplicate numbers in array
Wrote a little webapi knowledge points from 0 to 1
[QNX Hypervisor 2.2用户手册]9.7 generate
Redis expiration key deletion strategy [easy to understand]
MES系统设备管理概述(下)
Implementation of mesh parameterized least squares conformal maps (3D mesh mapping to 2D plane)