Fetch是全局對象window的一個方發,是XMLHttpRequest一個更現代化的替代方案。
Fetch暫時不支持abort request。
Fetch是基於promise的。
javascript
Fetch返回一個promise,能夠使用then來處理結果,或者搭配async/await使用。
let promise = fetch(url, [options])
java
先看一個最簡單的get用法示例:git
// url (required), options (optional) fetch('https://davidwalsh.name/some/url', { method: 'get' }).then(function(response) { // response.... }).catch(function(err) { // Error... }); 複製代碼
下面是一個稍微複雜的post用法示例:github
fetch(url, { method: 'POST', body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, credentials: "same-origin" }).then(function(response) { response.status //=> number 100-599 response.statusText //=> String response.headers //=> Headers response.url //=> String return response.text() }, function(error) { error.message //=> String }) 複製代碼
Fetch使用Promises來處理response。Fetch接收兩個參數:json
還能夠使用Request對象實例做爲參數的方式發起fetch請求:跨域
var request = new Request(url, options); fetch(request).then(function(response) { // handle with response... }).catch(function(err) { // Error... }); 複製代碼
options能夠配置如下參數:promise
{ body: new URLSearchParams([['foo', 1], ['bar', 2]]).toString() } 複製代碼
body的類型包括:瀏覽器
Class | Default Content-Type |
---|---|
String | text/plain;charset=UTF-8 |
URLSearchParams | application/x-www-form-urlencoded;charset=UTF-8 |
FormData | multipart/form-data |
Blob | inherited from the blob.type property |
ArrayBuffer | |
TypedArray | |
DataView |
其餘數據結構須要預先編碼爲上述類型之一。例如,JSON.stringify(data)可用於將數據結構序列化爲JSON字符串。bash
{ headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式爲表單提交 }) } 複製代碼
headers提供如下方法增刪改查頭部信息:服務器
Response表示來自服務器的HTTP響應。Response會做爲promise回調函數的參數。 包含如下屬性:
此外,response還提供了一些方法處理成特定的數據格式並返回一個Promise:
獲取響應一般須要通過兩個階段:
let response = await fetch('/article/fetch/logo-fetch.svg'); let blob = await response.blob(); // 以 Blob 對象下載 img.src = URL.createObjectURL(blob); 複製代碼
若是出現網絡錯誤或其餘緣由致使HTTP請求沒法完成,fetch()的promise 將會reject該error。 注意,在HTTP 4xx或5xx服務器響應的狀況下,promise不會reject。這個promise將像HTTP 2xx同樣正常resolve。能夠經過檢查response.status的狀態碼來決定如何處理錯誤:
fetch(...).then(function(response) { if (response.ok) { return response } else { var error = new Error(response.statusText) error.response = response throw error } }) 複製代碼
截至目前,fetch的瀏覽器兼容狀況以下圖所示: (能夠在can I use這個網站查詢瀏覽器兼容性)
若是想要兼容IE及老版本瀏覽器,能夠使用polyfill:whatwg-fetch