一、基本用法
fetch()的功能與 XMLHttpRequest 基本相同,但有三個主要的差異。
(1)fetch()使用 Promise,不使用回調函數,因此大大簡化了寫法,寫起來更簡潔。
(2)fetch()采用模塊化設計,API 分散在多個對象上(Response 對象、Request 對象、Headers 對象),更合理一些;相比之下,XMLHttpRequest 的 API 設計並不是很好,輸入、輸出、狀態都在同一個接口管理,容易寫出非常混亂的代碼。
(3)fetch()通過數據流(Stream 對象)處理數據,可以分塊讀取,有利於提高網站性能表現,減少內存占用,對於請求大文件或者網速慢的場景相當有用。XMLHTTPRequest 對象不支持數據流,所有的數據必須放在緩存里,不支持分塊讀取,必須等待全部拿到后,再一次性吐出來。
在用法上,fetch()接受一個 URL 字符串作為參數,默認向該網址發出 GET 請求,返回一個 Promise 對象。它的基本用法如下。
fetch(url) .then(...) .catch(...)
下面是一個例子,從服務器獲取 JSON 數據。
fetch('https://api.github.com/users/ruanyf') .then(response => response.json()) .then(json => console.log(json)) .catch(err => console.log('Request Failed', err));
上面示例中,fetch()接收到的response是一個 Stream 對象,response.json()是一個異步操作,取出所有內容,並將其轉為 JSON 對象。
Promise 可以使用 await 語法改寫,使得語義更清晰。
async function getJSON() { let url = 'https://api.github.com/users/ruanyf'; try { let response = await fetch(url); return await response.json(); } catch (error) { console.log('Request Failed', error); } }
上面示例中,await語句必須放在try...catch里面,這樣才能捕捉異步操作中可能發生的錯誤。
后文都采用await的寫法,不使用.then()的寫法。
二、Response 對象:處理 HTTP 回應
2.1 Response 對象的同步屬性
fetch()請求成功以后,得到的是一個 Response 對象。它對應服務器的 HTTP 回應。
const response = await fetch(url);
前面說過,Response 包含的數據通過 Stream 接口異步讀取,但是它還包含一些同步屬性,對應 HTTP 回應的標頭信息(Headers),可以立即讀取。
async function fetchText() { let response = await fetch('/readme.txt'); console.log(response.status); console.log(response.statusText); }
上面示例中,response.status和response.statusText就是 Response 的同步屬性,可以立即讀取。
標頭信息屬性有下面這些。
Response.ok
Response.ok屬性返回一個布爾值,表示請求是否成功,true對應 HTTP 請求的狀態碼 200 到 299,false對應其他的狀態碼。
Response.status
Response.status屬性返回一個數字,表示 HTTP 回應的狀態碼(例如200,表示成功請求)。
Response.statusText
Response.statusText屬性返回一個字符串,表示 HTTP 回應的狀態信息(例如請求成功以后,服務器返回"OK")。
Response.url
Response.url屬性返回請求的 URL。如果 URL 存在跳轉,該屬性返回的是最終 URL。
Response.type
Response.type屬性返回請求的類型。可能的值如下:
basic:普通請求,即同源請求。cors:跨域請求。error:網絡錯誤,主要用於 Service Worker。opaque:如果fetch()請求的type屬性設為no-cors,就會返回這個值,詳見請求部分。表示發出的是簡單的跨域請求,類似<form>表單的那種跨域請求。opaqueredirect:如果fetch()請求的redirect屬性設為manual,就會返回這個值,詳見請求部分。
Response.redirected
Response.redirected屬性返回一個布爾值,表示請求是否發生過跳轉。
2.2 判斷請求是否成功
fetch()發出請求以后,有一個很重要的注意點:只有網絡錯誤,或者無法連接時,fetch()才會報錯,其他情況都不會報錯,而是認為請求成功。
這就是說,即使服務器返回的狀態碼是 4xx 或 5xx,fetch()也不會報錯(即 Promise 不會變為 rejected狀態)。
只有通過Response.status屬性,得到 HTTP 回應的真實狀態碼,才能判斷請求是否成功。請看下面的例子。
async function fetchText() { let response = await fetch('/readme.txt'); if (response.status >= 200 && response.status < 300) { return await response.text(); } else { throw new Error(response.statusText); } }
上面示例中,response.status屬性只有等於 2xx (200~299),才能認定請求成功。這里不用考慮網址跳轉(狀態碼為 3xx),因為fetch()會將跳轉的狀態碼自動轉為 200。
另一種方法是判斷response.ok是否為true。
if (response.ok) { // 請求成功 } else { // 請求失敗 }
2.3 Response.headers 屬性
Response 對象還有一個Response.headers屬性,指向一個 Headers 對象,對應 HTTP 回應的所有標頭。
Headers 對象可以使用for...of循環進行遍歷。
const response = await fetch(url); for (let [key, value] of response.headers) { console.log(`${key} : ${value}`); } // 或者 for (let [key, value] of response.headers.entries()) { console.log(`${key} : ${value}`); }
Headers 對象提供了以下方法,用來操作標頭。
Headers.get():根據指定的鍵名,返回鍵值。Headers.has(): 返回一個布爾值,表示是否包含某個標頭。Headers.set():將指定的鍵名設置為新的鍵值,如果該鍵名不存在則會添加。Headers.append():添加標頭。Headers.delete():刪除標頭。Headers.keys():返回一個遍歷器,可以依次遍歷所有鍵名。Headers.values():返回一個遍歷器,可以依次遍歷所有鍵值。Headers.entries():返回一個遍歷器,可以依次遍歷所有鍵值對([key, value])。Headers.forEach():依次遍歷標頭,每個標頭都會執行一次參數函數。
上面的有些方法可以修改標頭,那是因為繼承自 Headers 接口。對於 HTTP 回應來說,修改標頭意義不大,況且很多標頭是只讀的,瀏覽器不允許修改。
這些方法中,最常用的是response.headers.get(),用於讀取某個標頭的值。
let response = await fetch(url); response.headers.get('Content-Type') // application/json; charset=utf-8
Headers.keys()和Headers.values()方法用來分別遍歷標頭的鍵名和鍵值。
// 鍵名 for(let key of myHeaders.keys()) { console.log(key); } // 鍵值 for(let value of myHeaders.values()) { console.log(value); }
Headers.forEach()方法也可以遍歷所有的鍵值和鍵名。
let response = await fetch(url); response.headers.forEach( (value, key) => console.log(key, ':', value) );
2.4 讀取內容的方法
Response對象根據服務器返回的不同類型的數據,提供了不同的讀取方法。
response.text():得到文本字符串。response.json():得到 JSON 對象。response.blob():得到二進制 Blob 對象。response.formData():得到 FormData 表單對象。response.arrayBuffer():得到二進制 ArrayBuffer 對象。
上面5個讀取方法都是異步的,返回的都是 Promise 對象。必須等到異步操作結束,才能得到服務器返回的完整數據。
response.text()
response.text()可以用於獲取文本數據,比如 HTML 文件。
const response = await fetch('/users.html'); const body = await response.text(); document.body.innerHTML = body
response.json()
response.json()主要用於獲取服務器返回的 JSON 數據,前面已經舉過例子了。
response.formData()
response.formData()主要用在 Service Worker 里面,攔截用戶提交的表單,修改某些數據以后,再提交給服務器。
response.blob()
response.blob()用於獲取二進制文件。
const response = await fetch('flower.jpg'); const myBlob = await response.blob(); const objectURL = URL.createObjectURL(myBlob); const myImage = document.querySelector('img'); myImage.src = objectURL;
上面示例讀取圖片文件flower.jpg,顯示在網頁上。
response.arrayBuffer()
response.arrayBuffer()主要用於獲取流媒體文件。
const audioCtx = new window.AudioContext(); const source = audioCtx.createBufferSource(); const response = await fetch('song.ogg'); const buffer = await response.arrayBuffer(); const decodeData = await audioCtx.decodeAudioData(buffer); source.buffer = buffer; source.connect(audioCtx.destination); source.loop = true;
上面示例是response.arrayBuffer()獲取音頻文件song.ogg,然后在線播放的例子。
2.5 Response.clone()
Stream 對象只能讀取一次,讀取完就沒了。這意味着,前一節的五個讀取方法,只能使用一個,否則會報錯。
let text = await response.text(); let json = await response.json(); // 報錯
上面示例先使用了response.text(),就把 Stream 讀完了。后面再調用response.json(),就沒有內容可讀了,所以報錯。
Response 對象提供Response.clone()方法,創建Response對象的副本,實現多次讀取。
const response1 = await fetch('flowers.jpg'); const response2 = response1.clone(); const myBlob1 = await response1.blob(); const myBlob2 = await response2.blob(); image1.src = URL.createObjectURL(myBlob1); image2.src = URL.createObjectURL(myBlob2);
上面示例中,response.clone()復制了一份 Response 對象,然后將同一張圖片讀取了兩次。
Response 對象還有一個Response.redirect()方法,用於將 Response 結果重定向到指定的 URL。該方法一般只用在 Service Worker 里面,這里就不介紹了。
2.6 Response.body 屬性
Response.body屬性是 Response 對象暴露出的底層接口,返回一個 ReadableStream 對象,供用戶操作。
它可以用來分塊讀取內容,應用之一就是顯示下載的進度。
const response = await fetch('flower.jpg'); const reader = response.body.getReader(); while(true) { const {done, value} = await reader.read(); if (done) { break; } console.log(`Received ${value.length} bytes`) }
上面示例中,response.body.getReader()方法返回一個遍歷器。這個遍歷器的read()方法每次返回一個對象,表示本次讀取的內容塊。
這個對象的done屬性是一個布爾值,用來判斷有沒有讀完;value屬性是一個 arrayBuffer 數組,表示內容塊的內容,而value.length屬性是當前塊的大小。
三、fetch()的第二個參數:定制 HTTP 請求
fetch()的第一個參數是 URL,還可以接受第二個參數,作為配置對象,定制發出的 HTTP 請求。
fetch(url, optionObj)
上面命令的optionObj就是第二個參數。
HTTP 請求的方法、標頭、數據體都在這個對象里面設置。下面是一些示例。
(1)POST 請求
const response = await fetch(url, { method: 'POST', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8", }, body: 'foo=bar&lorem=ipsum', }); const json = await response.json();
上面示例中,配置對象用到了三個屬性。
method:HTTP 請求的方法,POST、DELETE、PUT都在這個屬性設置。headers:一個對象,用來定制 HTTP 請求的標頭。body:POST 請求的數據體。
注意,有些標頭不能通過headers屬性設置,比如Content-Length、Cookie、Host等等。它們是由瀏覽器自動生成,無法修改。
(2)提交 JSON 數據
const user = { name: 'John', surname: 'Smith' }; const response = await fetch('/article/fetch/post/user', { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(user) });
上面示例中,標頭Content-Type要設成'application/json;charset=utf-8'。因為默認發送的是純文本,Content-Type的默認值是'text/plain;charset=UTF-8'。
(3)提交表單
const form = document.querySelector('form'); const response = await fetch('/users', { method: 'POST', body: new FormData(form) })
(4)文件上傳
如果表單里面有文件選擇器,可以用前一個例子的寫法,上傳的文件包含在整個表單里面,一起提交。
另一種方法是用腳本添加文件,構造出一個表單,進行上傳,請看下面的例子。
const input = document.querySelector('input[type="file"]'); const data = new FormData(); data.append('file', input.files[0]); data.append('user', 'foo'); fetch('/avatars', { method: 'POST', body: data });
上傳二進制文件時,不用修改標頭的Content-Type,瀏覽器會自動設置。
(5)直接上傳二進制數據
fetch()也可以直接上傳二進制數據,將 Blob 或 arrayBuffer 數據放在body屬性里面。
let blob = await new Promise(resolve => canvasElem.toBlob(resolve, 'image/png') ); let response = await fetch('/article/fetch/post/image', { method: 'POST', body: blob });
