Fetch概念
fetch身為H5中的一個新對象,他的誕生,是為了取代ajax的存在而出現(xiàn),主要目的僅僅只是為了結(jié)合ServiceWorkers,來達(dá)到以下優(yōu)化:
- 優(yōu)化離線體驗
- 保持可擴(kuò)展性
當(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的不同點(diǎn):
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é)果
![](/d/20211016/006ef323a314c57914be8b6d195f7f46.gif)
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í)有所幫助,也希望大家多多支持腳本之家。