浅谈Fetch 数据交互方式
获取资源很简单,发起一个请求出去,一个响应进来,然后该怎么操作就怎么操作。
fetch的api使用的是promise规范,不会promise(用于延迟(deferred)计算和异步(asynchronous)计算。一个Promise对象代表着一个还未完成,但预期将来会完成的操作。主要使用它处理回调黑洞。)的请花几分钟学习一下。
使用fetch去获取数据的方式:
fetch("服务器地址")
.then(function(response){
//将获取到的数据使用json转换对象
returnresponse.json();
})
.then(function(data){
//获取转换后的格式
console.log(data);
})
//如果有异常会在catch捕获
.catch(function(e){
console.log("error");
});
有没有发现使用fetch后代码变优美了,不关心数据怎么请求的,把更多的精力放在处理数据上。
不用写回调函数了,也不用监听xhrreadystatechange事件了,当数据请求回来后会传递给then,有异常就会直接触发catch事件。
fetch默认发起的是get请求,如果需要post请求需要设置Request
Request
Request客户端向服务器发出请求的一个对象,包括用户提交的信息以及客户端的一些信息
使用Request构造一个fetch请求的对象的详细信息
//实例化request对象
varmyRequest=newRequest(url,Option);
fetch(myRequest)
.then(function(response){
console.log(response);
})
//如果有异常会在catch捕获
.catch(function(e){
console.log("error");
});
Request详细参数配置:
method
设置请求方式
method=GET/POST/PUT/DELETE/HEAD
headers
设置请求头信息,使用Headers对象
letheaders=newHeaders({
'Content-Type':'text/plain'
});
mode
请求的模式,主要用于跨域设置
mode=cors/no-cors/same-origin
cors:跨域
no-cors:不跨域
same-origin:同源
credentials
需要向服务器发送cookie时设置
credentials=omit/same-origin
omit:省略
same-origin:发送同源cookie
cache
cache=default/reload/no-cache
redirect
收到重定向消息时如何处理
redirect=follow/error/manual
follow:跟随重定向的地址,继续请求
error:不请求
比如:
varrequest=newRequest("url",{
headers:newHeaders({
"Content-Type":"text/plain"
}),
method:"POST",
mode:"cors",
redirect:"follow"
});
fetch(request)
.then((response)=>{
console.log(response);
})
.catch((error)=>{
console.log(error);
});
fetch数据处理
当fetch把请求结果拿到后,我们需要使用它提供的几个方法来做处理
json
fetch提供了一个json方法将数据转换为json格式
fetch(url)
.then((response)=>{
//返回object类型
returnresponse.json();
})
.then((result)=>{
console.log(result);
});
text
fetch提供了一个text方法用于获取数据,返回的是string格式数据
fetch(url)
.then((response)=>{
//返回string类型
returnresponse.text();
})
.then((result)=>{
console.log(result);
});
blob
如果我们获取的是一个图像,需要先设置头信息,然后fetch会正常处理本次请求,最终使用blob方法获取本次请求的结果,可以把结果赋值给imgsrc就能正常的显示一张图片
varrequest=newRequest("xx.img",{
headers:newHeaders({
"Content-Type":"image/jpeg"
}),
method:"get",
cache:'default'
});
fetch(request)
.then((response)=>{
returnresponse.blob();
})
.then((stories)=>{
varobjectURL=URL.createObjectURL(stories);
letimg=document.createElement("img");
img.src=objectURL;
document.querySelector("body").appendChild(img);
});
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。