Fetch定义
fetch身为H5中的1个新目标,他的诞生,是以便替代ajax的存在而出現,关键目地仅仅只是以便融合ServiceWorkers,来做到下列提升:
- 提升线下体验
- 维持可拓展性
自然假如ServiceWorkers和访问器端数据信息库IndexedDB相互配合,那末恭贺你,每个访问器都可以以变成1个代理商服务器1样的存在。(但是我其实不觉得这样是好事儿,这样会使得前端开发愈来愈重,走之前c/s构架的老路)
1. 序言
既然是h5的新方式,毫无疑问就有1些较为older的访问器不适用了,针对那些不适用此方式的
访问器就必须附加的加上1个polyfill:
[连接]: https://github.com/fis-components/whatwg-fetch
2. 用法
ferch(抓取) :
HTML:
fetch('/users.html') //这里回到的是1个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) { //分辨回应的情况码是不是一切正常 return response //一切正常回到原回应目标 } else { var error = new Error(response.statusText) //不一切正常则抛出1个回应不正确情况信息内容 error.response = response throw error } } function parseJSON(response) { return response.json() } fetch('/users') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('request succeeded with JSON response', data) }).catch(function(error) { console.log('request failed', error) })
2.1个很重要的难题,fetch方式不容易推送cookie,这针对必须维持顾客端和服务器端常联接就很致命了,由于服务器端必须根据cookie来鉴别某1个session来做到维持对话情况.要想推送cookie必须改动1下信息内容:
fetch('/users', { credentials: 'same-origin' //同域下推送cookie }) fetch('https://segmentfault.com', { credentials: 'include' //跨域下推送cookie })
下图是跨域浏览segment的結果
Additional
假如不出出现意外的话,恳求的url和回应的url是同样的,可是假如像redirect这类实际操作的话response.url将会就会不1样.在XHR时,redirect后的response.url将会就不太精确了,必须设定下:response.headers['X-Request-URL'] = request.url可用于( Firefox < 32, Chrome < 37, Safari, or IE.)
以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。