Fetch概念
fetch身為H5中的一個新對象,他的誕生,是為了取代ajax的存在而出現(xiàn),主要目的僅僅只是為了結(jié)合ServiceWorkers,來達(dá)到以下優(yōu)化:
當(dāng)然如果ServiceWorkers和瀏覽器端的數(shù)據(jù)庫IndexedDB配合,那么恭喜你,每一個瀏覽器都可以成為一個代理服務(wù)器一樣的存在。(然而我并不認(rèn)為這樣是好事,這樣會使得前端越來越重,走以前c/s架構(gòu)的老路)
1. 前言
既然是h5的新方法,肯定就有一些比較older的瀏覽器不支持了,對于那些不支持此方法的
瀏覽器就需要額外的添加一個polyfill:
[鏈接]: https://github.com/fis-components/whatwg-fetch
2. 用法
ferch(抓取) :
HTML:
fetch('/users.html') //這里返回的是一個Promise對象,不支持的瀏覽器需要相應(yīng)的ployfill或通過babel等轉(zhuǎn)碼器轉(zhuǎn)碼后在執(zhí)行 .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]) //這里獲取選擇的文件內(nèi)容 data.append('user', 'hubot') fetch('/avatars', { method: 'POST', body: data })
3. 注意事項
(1)和ajax的不同點:
1. fatch方法抓取數(shù)據(jù)時不會拋出錯誤即使是404或500錯誤,除非是網(wǎng)絡(luò)錯誤或者請求過程中被打斷.但當(dāng)然有解決方法啦,下面是demonstration:
function checkStatus(response) { if (response.status >= 200 && response.status < 300) { //判斷響應(yīng)的狀態(tài)碼是否正常 return response //正常返回原響應(yīng)對象 } else { var error = new Error(response.statusText) //不正常則拋出一個響應(yīng)錯誤狀態(tài)信息 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.一個很關(guān)鍵的問題,fetch方法不會發(fā)送cookie,這對于需要保持客戶端和服務(wù)器端常連接就很致命了,因為服務(wù)器端需要通過cookie來識別某一個session來達(dá)到保持會話狀態(tài).要想發(fā)送cookie需要修改一下信息:
fetch('/users', { credentials: 'same-origin' //同域下發(fā)送cookie }) fetch('https://segmentfault.com', { credentials: 'include' //跨域下發(fā)送cookie })
下圖是跨域訪問segment的結(jié)果
Additional
如果不出意外的話,請求的url和響應(yīng)的url是相同的,但是如果像redirect這種操作的話response.url可能就會不一樣.在XHR時,redirect后的response.url可能就不太準(zhǔn)確了,需要設(shè)置下:response.headers['X-Request-URL'] = request.url適用于( Firefox < 32, Chrome < 37, Safari, or IE.)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:廣西 淮安 佳木斯 咸寧 西寧 南京 酒泉 十堰
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《關(guān)于h5中的fetch方法解讀(小結(jié))》,本文關(guān)鍵詞 關(guān)于,中的,fetch,方法,解讀,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。