关于h5中的fetch方法解读(小结)

2020-04-21 22:56:45易采站长站整理

Fetch概念

fetch身为H5中的一个新对象,他的诞生,是为了取代ajax的存在而出现,主要目的仅仅只是为了结合ServiceWorkers,来达到以下优化:

优化离线体验
保持可扩展性

当然如果ServiceWorkers和浏览器端的数据库IndexedDB配合,那么恭喜你,每一个浏览器都可以成为一个代理服务器一样的存在。(然而我并不认为这样是好事,这样会使得前端越来越重,走以前c/s架构的老路)

1. 前言

既然是h5的新方法,肯定就有一些比较older的浏览器不支持了,对于那些不支持此方法的

浏览器就需要额外的添加一个polyfill:

[链接]: https://github.com/fis-components/whatwg-fetch

2. 用法

ferch(抓取) :

HTML:


fetch('/users.html') //这里返回的是一个Promise对象,不支持的浏览器需要相应的ployfill或通过babel等转码器转码后在执行
.then(function(response) {
return response.text()})
.then(function(body) {
document.body.innerHTML = body
})

JSON : 


fetch('/users.json')
.then(function(response) {
return response.json()})
.then(function(json) {
console.log('parsed json', json)})
.catch(function(ex) {
console.log('parsing failed', ex)
})

Response metadata :


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)
})

Post form:


var form = document.querySelector('form')

fetch('/users', {
method: 'POST',
body: new FormData(form)
})

Post JSON:


fetch('/users', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ //这里是post请求的请求体
name: 'Hubot',
login: 'hubot',
})
})

File upload:


var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0]) //这里获取选择的文件内容
data.append('user', 'hubot')

fetch('/avatars', {
method: 'POST',
body: data
})

3. 注意事项

(1)和ajax的不同点:

1. fatch方法抓取数据时不会抛出错误即使是404或500错误,除非是网络错误或者请求过程中被打断.但当然有解决方法啦,下面是demonstration:


function checkStatus(response) {
if (response.status >= 200 && response.status < 300) { //判断响应的状态码是否正常