当前位置:网站首页>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'
})边栏推荐
- Mongodb query and projection operators
- Source code of wechat applet for discerning flowers and plants / source code of wechat applet for discerning plants
- 关于优先队列
- Strategy mode_
- EasyExcel实用技巧
- Take away applet with main version of traffic / repair to add main access function of traffic
- CSV generated by PHP cannot completely display the number with leading 0
- @Autowired注解 required属性
- Call Gaode map -- address is converted into longitude and latitude
- ETL工具(数据同步) 二
猜你喜欢

Learning exploration - waves

Wamp MySQL empty password

Very simple vsplayaudio online music player plug-in
![[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

Network Security Learning notes-1 file upload

Why are there many snapshot tables in the BI system?

谷粒学苑P98踩坑 e.GlobalExceptionHandler : null

【代码案例】博客页面设计(附完整源码)

自定义mvc原理

Discuz magazine / news report template (jeavi_line) utf8 GBK / DZ template download
随机推荐
类和对象(2)(6个默认成员函数)
The difference between MySQL clustered index and non clustered index
CTS测试方法「建议收藏」
How to set pseudo static for WordPress fixed links
PHP JSON variable array problem
PHP wechat scan code, follow official account and authorize login source code
Redis过期键的删除策略[通俗易懂]
WebMvcConfigurationSupport
JS get the current date and time
[QNX Hypervisor 2.2用户手册]9.7 generate
Multimodal deep multi modal sets
File contains vulnerability
Tips for using (1)
CTS test method "suggestions collection"
1913. 两个数对之间的最大乘积差-无需排序法
Call Gaode map -- address is converted into longitude and latitude
Which securities firm is the best and safest for beginners to open an account
General paging function
策略模式_
加拿大EE通道