关于fetch
- fetch函数属于全局对象 可以直接调用 返回的结果是一个promise对象
- 当接收到一个代表错误的 HTTP 状态码时,从
fetch()
返回的 Promise 不会被标记为reject
,即使响应的 HTTP 状态码是 404 或 500。相反,它会将 Promise 状态标记为resolve
(如果响应的 HTTP 状态码不在 200 - 299 的范围内,则设置resolve
返回值的ok
属性为false
),仅当网络故障时或请求被阻止时,才会标记为reject
。
设置fetch请求
通过网络获取一个 JSON 文件并将其打印到控制台:
“最简单的用法是只提供一个参数用来指明想 fetch() 到的资源路径,然后返回一个包含响应结果的 promise(一个 Response 对象)。”
fetch('http://localhost:8000/fetch-server?vip=11',{
// 请求方法
method:'POST',
// 请求头
headers:{
name:'xiaoming'
},
// 请求体
body:'username=admin&password=admin'
}).then(response => { // 响应
// text():返回的类型为字符串,无法通过键名来获取响应的值
// return response.text();
// json():返回类型为字典,可以通过键名来获取响应的值
return response.json();
}).then(response => {
console.log(response);
})
fetch的两个then()
- fetch() 的第一个 then 执行第一个 resolve 回调函数,函数参数为 Response 对象,怎么处理返回的对象呢?
“直接输出 Response 对象不是我们需要的数据,使用response.json()或者response.text()等方法获取到我们需要的数据。” - 第二个then获取并处理数据
实现fetch超时设置
原生的fetch并不支持超时设置(没有timeout配置)
实现:Promise.race() + 一个reject()的Promise + setTimeout()
<button id="timer">超时fetch</button>
const timer = document.getElementById("timer");
function _fetch(fetch_promise, timeout) {
var abort_fn = null;
// 这是一个可以被reject的promise
var abort_promise = new Promise((res, rej) => {
abort_fn = function() {
rej('abort promise');
};
});
//这里使用Promise.race,以最快 resolve 或 reject 的结果来传入后续绑定的回调
var abortable_promise = Promise.race([
fetch_promise,
abort_promise
]);
setTimeout(function() {
abort_fn();
}, timeout);
return abortable_promise;
}
timer.addEventListener('click', function() {
_fetch(fetch('http://localhost:8000/fetch-server?vip=11'), 2000).then(
function(res) {
console.log('res的结果');
console.log(res);
}, function(err) {
console.log('err的结果');
console.log(err);
});
});
fetch和ajax的区别
- ajax基于原生的XHR,XHR本身的开发架构不清晰,fetch采用了Promise的异步处理机制,使用比ajax简单;
- ajax利用XMLHttpRequest对象来请求数据,fetch只是全局对象window的一个方法。
- fetch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理
- fetch没有办法原生监测请求的进度,而XHR可以
- 默认情况下,fetch在不会接受和发送cookie,如果需要发送cookie的话,此时需要对其单独进行配置。
以POST请求为例,ajax发送请求代码如下:
// 1.创建对象
const xhr=new XMLHttpRequest();
// 2.初始化,设置类型与URL
xhr.open('POST','http://localhost:8000/server');
// 设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 自定义请求头
xhr.setRequestHeader('name','atguigu')
// 3.发送
//xhr.send();
// 设置请求体
xhr.send('a=100&b=200');
// xhr.send('a:100&b:200&c:300');
// xhr.send('123456');
// 4.事件绑定
xhr.onreadystatechange=function(){
// 判断
if(xhr.readyState===4){
if(xhr.status>=200 && xhr.status<300){
// 处理服务器返回的结果
result.innerHTML=xhr.response;
}
}
}