赞
踩
fetch() 是一个全局方法,提供一种简单,合理的方式跨网络获取资源。它的请求是基于 Promise 的,需要详细学习 Promise ,请点击《 Promise详解 》。它是专门为了取代传统的 xhr 而生的。
1.1、fetch使用语法
- fetch(url,options).then((response)=>{
- //处理http响应
- },(error)=>{
- //处理错误
- })
url :是发送网络请求的地址。
options:发送请求参数,
1.2、response 对象
fetch 请求成功后,响应 response 对象如图:
1.3、读取内容方法
response 对象根据服务器返回的不同类型数据,提供了不同的读取方法。分别有:
上述 5 个方法,返回的都是 promise 对象,必须等到异步操作结束,才能得到服务器返回的完整数据。
1.4、response.clone()
stream 对象只能读取一次,读取完就没了,这意味着,上边的五种读取方法,只能使用一个,否则会报错。
因此 response 对象提供了 clone() 方法,创建 respons 对象副本,实现多次读取。如下:将一张图片,读取两次:
const response1 = await fetch('flowers.jpg'); const response2 = response1.clone(); const myBlob1 = await response1.blob(); const myBlob2 = await response2.blob(); image1.src = URL.createObjectURL(myBlob1); image2.src = URL.createObjectURL(myBlob2);
1.5、response.body()
body 属性返回一个 ReadableStream 对象,供用户操作,可以用来分块读取内容,显示下载的进度就是其中一种应用。
const response = await fetch('flower.jpg'); const reader = response.body.getReader(); while(true) { const {done, value} = await reader.read(); if (done) { break; } console.log(`Received ${value.length} bytes`) }
response.body.getReader() 返回一个遍历器,这个遍历器 read() 方法每次都会返回一个对象,表示本次读取的内容块。
请求方式不同,传值方式也不同。xhr 会分别处理 get 和 post 数据传输,还有请求头设置,同样 fetch 也需要分别处理。
2.1、get 方式
只需要在url中加入传输数据,options中加入请求方式。如下面代码所示:
<input type="text" id="user"><br> <input type="password" id="pas"><br> <button οnclick="login()">提交</button> <script> function login(){ fetch(`http://localhost:80/fetch.html?user=${user.value}&pas=${pas.value}`,{ method:'GET' }).then(response=>{ console.log('响应',response) }) } </script>
2.2、post 方式
使用 post 发送请求时,需要设置请求头、请求数据等。
将上个实例,改写成 post 方式提交数据,代码如下:
fetch(`http://localhost:80/ES6练习题/53fetch.html`,{ method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8' }, body:`user=${user.value}&pas=${pas.value}` }).then(response=>{ console.log('响应',response) })
如果是提交json数据时,需要把json转换成字符串。如
body:JSON.stringify(json)
如果提交的是表单数据,使用 formData转化下,如:
body:new FormData(form)
上传文件,可以包含在整个表单里一起提交,如:
const input = document.querySelector('input[type="file"]'); const data = new FormData(); data.append('file', input.files[0]); data.append('user', 'foo'); fetch('/avatars', { method: 'POST', body: data });
上传二进制数据,将 bolb 或 arrayBuffer 数据放到body属性里,如:
let blob = await new Promise(resolve => canvasElem.toBlob(resolve, 'image/png') ); let response = await fetch('/article/fetch/post/image', { method: 'POST', body: blob });
3.1、fetch兼容性
fetch原生支持率如图:
fetch 是相对较新的技术,IE浏览器不支持,还有其他低版本浏览器也不支持,因此如果使用fetch时,需要考虑浏览器兼容问题。
解决办法:引入 polyfill 完美支持 IE8 以上。
polyfill 的原理就是探测fetch是否支持,如果不支持则用 xhr 实现。支持 fetch 的浏览器,响应中文会乱码,所以使用 fetch-detector 和 fetch-ie8 解决乱码问题。
3.2、fetch默认不带cookie
传递cookie时,必须在header参数内加上 credentials:'include',才会像 xhr 将当前cookie 带有请求中。
3.3、异常处理
fetch 不同于 xhr ,xhr 自带取消、错误等方法,所以服务器返回 4xx 或 5xx 时,是不会抛出错误的,需要手动处理,通过 response 中的 status 字段来判断。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。