https://www.jb51.net/html5/586989.html
https://segmentfault.com/a/1190000011973904
Fetch概念
fetch身爲H5中的一個新對象,他的誕生,是爲了取代ajax的存在而出現,主要目的僅僅只是爲了結合ServiceWorkers,來達到以下優化:
- 優化離線體驗
- 保持可擴展性
當然如果ServiceWorkers和瀏覽器端的數據庫IndexedDB配合,那麼恭喜你,每一個瀏覽器都可以成爲一個代理服務器一樣的存在。(然而我並不認爲這樣是好事,這樣會使得前端越來越重,走以前c/s架構的老路)
1. 前言
既然是h5的新方法,肯定就有一些比較older的瀏覽器不支持了,對於那些不支持此方法的
瀏覽器就需要額外的添加一個polyfill:
[鏈接]: https://github.com/fis-components/whatwg-fetch
2. 用法
ferch(抓取) :
HTML:
?
1
2
3
4
5
6
|
fetch('/users.html') //這裏返回的是一個Promise對象,不支持的瀏覽器需要相應的ployfill或通過babel等轉碼器轉碼後在執行
.then(function(response) {
return response.text()})
.then(function(body) {
document.body.innerHTML = body
})
|
JSON :
?
1
2
3
4
5
6
7
8
|
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 :
?
1
2
3
4
5
6
|
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:
?
1
2
3
4
5
6
|
var form = document.querySelector( 'form' )
fetch( '/users' , {
method: 'POST' ,
body: new FormData(form)
})
|
Post JSON:
?
1
2
3
4
5
6
7
8
9
10
11
|
fetch( '/users' , {
method: 'POST' ,
headers: {
'Accept' : 'application/json' ,
'Content-Type' : 'application/json'
},
body: JSON.stringify({ //這裏是post請求的請求體
name: 'Hubot' ,
login: 'hubot' ,
})
})
|
File upload:
?
1
2
3
4
5
6
7
8
9
10
|
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:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) { //判斷響應的狀態碼是否正常
return response //正常返回原響應對象
} else {
var error = new Error(response.statusText) //不正常則拋出一個響應錯誤狀態信息
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.一個很關鍵的問題,fetch方法不會發送cookie,這對於需要保持客戶端和服務器端常連接就很致命了,因爲服務器端需要通過cookie來識別某一個session來達到保持會話狀態.要想發送cookie需要修改一下信息:
?
1
2
3
4
5
6
|
fetch( '/users' , {
credentials: 'same-origin' //同域下發送cookie
})
fetch( 'https://segmentfault.com' , {
credentials: 'include' //跨域下發送cookie
})
|
下圖是跨域訪問segment的結果
Additional
如果不出意外的話,請求的url和響應的url是相同的,但是如果像redirect這種操作的話response.url可能就會不一樣.在XHR時,redirect後的response.url可能就不太準確了,需要設置下:response.headers['X-Request-URL'] = request.url適用於( Firefox < 32, Chrome < 37, Safari, or IE.)