浅谈Fetch 数据交互方式

获取资源很简单,发起一个请求出去,一个响应进来,然后该怎么操作就怎么操作。

fetch 的 api 使用的是 promise 规范,不会 promise(用于延迟(deferred) 计算和异步(asynchronous ) 计算。 一个 Promise 对象代表着一个还未完成,但预期将来会完成的操作。主要使用它处理回调黑洞。) 的请花几分钟学习一下。

使用 fetch 去获取数据的方式:

fetch("服务器地址") .then(function(response) { //将获取到的数据使用 json 转换对象 return response.json(); }) .then(function(data) { //获取转换后的格式 console.log(data); }) //如果有异常会在 catch 捕获 .catch(function(e) { console.log("error"); });

有没有发现使用 fetch 后代码变优美了,不关心数据怎么请求的,把更多的精力放在处理数据上。

不用写回调函数了,也不用监听 xhr readystatechange 事件了,当数据请求回来后会传递给 then, 有异常就会直接触发 catch 事件。

fetch 默认发起的是 get 请求,如果需要 post 请求需要设置 Request

Request

Request 客户端向服务器发出请求的一个对象,包括用户提交的信息以及客户端的一些信息

使用 Request 构造一个 fetch 请求的对象的详细信息

//实例化 request 对象 var myRequest = new Request(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 对象

let headers = new Headers({ '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 : 不请求

比如:

var request = new Request("url", { headers: new Headers({ "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 类型 return response.json(); }) .then((result) => { console.log(result); });

text

fetch 提供了一个 text 方法用于获取数据,返回的是 string 格式数据

fetch(url) .then((response) => { //返回 string 类型 return response.text(); }) .then((result) => { console.log(result); });  

blob

如果我们获取的是一个图像,需要先设置头信息,然后 fetch 会正常处理本次请求,最终使用 blob 方法获取本次请求的结果, 可以把结果赋值给 img src 就能正常的显示一张图片

var request = new Request("xx.img", { headers: new Headers({ "Content-Type": "image/jpeg" }), method : "get", cache: 'default' }); fetch(request) .then((response) => { return response.blob(); }) .then((stories)=>{ var objectURL = URL.createObjectURL(stories); let img = document.createElement("img"); img.src = objectURL; document.querySelector("body").appendChild(img); });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/d295c28ad814401c60a53fc6be8e7df2.html