<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Fetch API 教程 `fetch()`是 XMLHttpRequest 的升級版,用于在 JavaScript 腳本里面發出 HTTP 請求。 瀏覽器原生提供這個對象。本章詳細介紹它的用法。 ## 基本用法 `fetch()`的功能與 XMLHttpRequest 基本相同,但有三個主要的差異。 (1)`fetch()`使用 Promise,不使用回調函數,因此大大簡化了寫法,寫起來更簡潔。 (2)`fetch()`采用模塊化設計,API 分散在多個對象上(Response 對象、Request 對象、Headers 對象),更合理一些;相比之下,XMLHttpRequest 的 API 設計并不是很好,輸入、輸出、狀態都在同一個接口管理,容易寫出非常混亂的代碼。 (3)`fetch()`通過數據流(Stream 對象)處理數據,可以分塊讀取,有利于提高網站性能表現,減少內存占用,對于請求大文件或者網速慢的場景相當有用。XMLHTTPRequest 對象不支持數據流,所有的數據必須放在緩存里,不支持分塊讀取,必須等待全部拿到后,再一次性吐出來。 在用法上,`fetch()`接受一個 URL 字符串作為參數,默認向該網址發出 GET 請求,返回一個 Promise 對象。它的基本用法如下。 ```javascript fetch(url) .then(...) .catch(...) ``` 下面是一個例子,從服務器獲取 JSON 數據。 ```javascript 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 對象](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API),`response.json()`是一個異步操作,取出所有內容,并將其轉為 JSON 對象。 Promise 可以使用 await 語法改寫,使得語義更清晰。 ```javascript 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 回應 ### Response 對象的同步屬性 `fetch()`請求成功以后,得到的是一個 [Response 對象](https://developer.mozilla.org/en-US/docs/Web/API/Response)。它對應服務器的 HTTP 回應。 ```javascript const response = await fetch(url); ``` 前面說過,Response 包含的數據通過 Stream 接口異步讀取,但是它還包含一些同步屬性,對應 HTTP 回應的標頭信息(Headers),可以立即讀取。 ```javascript 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`屬性返回一個布爾值,表示請求是否發生過跳轉。 ### 判斷請求是否成功 `fetch()`發出請求以后,有一個很重要的注意點:只有網絡錯誤,或者無法連接時,`fetch()`才會報錯,其他情況都不會報錯,而是認為請求成功。 這就是說,即使服務器返回的狀態碼是 4xx 或 5xx,`fetch()`也不會報錯(即 Promise 不會變為 `rejected`狀態)。 只有通過`Response.status`屬性,得到 HTTP 回應的真實狀態碼,才能判斷請求是否成功。請看下面的例子。 ```javascript 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`。 ```javascript if (response.ok) { // 請求成功 } else { // 請求失敗 } ``` ### Response.headers 屬性 Response 對象還有一個`Response.headers`屬性,指向一個 [Headers 對象](https://developer.mozilla.org/en-US/docs/Web/API/Headers),對應 HTTP 回應的所有標頭。 Headers 對象可以使用`for...of`循環進行遍歷。 ```javascript 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()`,用于讀取某個標頭的值。 ```javascript let response = await fetch(url); response.headers.get('Content-Type') // application/json; charset=utf-8 ``` `Headers.keys()`和`Headers.values()`方法用來分別遍歷標頭的鍵名和鍵值。 ```javascript // 鍵名 for(let key of myHeaders.keys()) { console.log(key); } // 鍵值 for(let value of myHeaders.values()) { console.log(value); } ``` `Headers.forEach()`方法也可以遍歷所有的鍵值和鍵名。 ```javascript let response = await fetch(url); response.headers.forEach( (value, key) => console.log(key, ':', value) ); ``` ### 讀取內容的方法 `Response`對象根據服務器返回的不同類型的數據,提供了不同的讀取方法。 > - `response.text()`:得到文本字符串。 > - `response.json()`:得到 JSON 對象。 > - `response.blob()`:得到二進制 Blob 對象。 > - `response.formData()`:得到 FormData 表單對象。 > - `response.arrayBuffer()`:得到二進制 ArrayBuffer 對象。 上面5個讀取方法都是異步的,返回的都是 Promise 對象。必須等到異步操作結束,才能得到服務器返回的完整數據。 **response.text()** `response.text()`可以用于獲取文本數據,比如 HTML 文件。 ```javascript 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()`用于獲取二進制文件。 ```javascript 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()`主要用于獲取流媒體文件。 ```javascript 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`,然后在線播放的例子。 ### Response.clone() Stream 對象只能讀取一次,讀取完就沒了。這意味著,前一節的五個讀取方法,只能使用一個,否則會報錯。 ```javascript let text = await response.text(); let json = await response.json(); // 報錯 ``` 上面示例先使用了`response.text()`,就把 Stream 讀完了。后面再調用`response.json()`,就沒有內容可讀了,所以報錯。 Response 對象提供`Response.clone()`方法,創建`Response`對象的副本,實現多次讀取。 ```javascript 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 里面,這里就不介紹了。 ### Response.body 屬性 `Response.body`屬性是 Response 對象暴露出的底層接口,返回一個 ReadableStream 對象,供用戶操作。 它可以用來分塊讀取內容,應用之一就是顯示下載的進度。 ```javascript 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 請求。 ```javascript fetch(url, optionObj) ``` 上面命令的`optionObj`就是第二個參數。 HTTP 請求的方法、標頭、數據體都在這個對象里面設置。下面是一些示例。 **(1)POST 請求** ```javascript 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 數據** ```javascript 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)提交表單** ```javascript const form = document.querySelector('form'); const response = await fetch('/users', { method: 'POST', body: new FormData(form) }) ``` **(4)文件上傳** 如果表單里面有文件選擇器,可以用前一個例子的寫法,上傳的文件包含在整個表單里面,一起提交。 另一種方法是用腳本添加文件,構造出一個表單,進行上傳,請看下面的例子。 ```javascript 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`屬性里面。 ```javascript let blob = await new Promise(resolve => canvasElem.toBlob(resolve, 'image/png') ); let response = await fetch('/article/fetch/post/image', { method: 'POST', body: blob }); ``` ## `fetch()`配置對象的完整 API `fetch()`第二個參數的完整 API 如下。 ```javascript const response = fetch(url, { method: "GET", headers: { "Content-Type": "text/plain;charset=UTF-8" }, body: undefined, referrer: "about:client", referrerPolicy: "no-referrer-when-downgrade", mode: "cors", credentials: "same-origin", cache: "default", redirect: "follow", integrity: "", keepalive: false, signal: undefined }); ``` `fetch()`請求的底層用的是 [Request() 對象](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)的接口,參數完全一樣,因此上面的 API 也是`Request()`的 API。 這些屬性里面,`headers`、`body`、`method`前面已經給過示例了,下面是其他屬性的介紹。 **cache** `cache`屬性指定如何處理緩存。可能的取值如下: - `default`:默認值,先在緩存里面尋找匹配的請求。 - `no-store`:直接請求遠程服務器,并且不更新緩存。 - `reload`:直接請求遠程服務器,并且更新緩存。 - `no-cache`:將服務器資源跟本地緩存進行比較,有新的版本才使用服務器資源,否則使用緩存。 - `force-cache`:緩存優先,只有不存在緩存的情況下,才請求遠程服務器。 - `only-if-cached`:只檢查緩存,如果緩存里面不存在,將返回504錯誤。 **mode** `mode`屬性指定請求的模式。可能的取值如下: - `cors`:默認值,允許跨域請求。 - `same-origin`:只允許同源請求。 - `no-cors`:請求方法只限于 GET、POST 和 HEAD,并且只能使用有限的幾個簡單標頭,不能添加跨域的復雜標頭,相當于提交表單、`<script>`加載腳本、`<img>`加載圖片等傳統的跨域請求方法。 **credentials** `credentials`屬性指定是否發送 Cookie。可能的取值如下: - `same-origin`:默認值,同源請求時發送 Cookie,跨域請求時不發送。 - `include`:不管同源請求,還是跨域請求,一律發送 Cookie。 - `omit`:一律不發送。 跨域請求發送 Cookie,需要將`credentials`屬性設為`include`。 ```javascript fetch('http://another.com', { credentials: "include" }); ``` **signal** `signal`屬性指定一個 AbortSignal 實例,用于取消`fetch()`請求,詳見下一節。 **keepalive** `keepalive`屬性用于頁面卸載時,告訴瀏覽器在后臺保持連接,繼續發送數據。 一個典型的場景就是,用戶離開網頁時,腳本向服務器提交一些用戶行為的統計信息。這時,如果不用`keepalive`屬性,數據可能無法發送,因為瀏覽器已經把頁面卸載了。 ```javascript window.onunload = function() { fetch('/analytics', { method: 'POST', body: "statistics", keepalive: true }); }; ``` **redirect** `redirect`屬性指定 HTTP 跳轉的處理方法。可能的取值如下: - `follow`:默認值,`fetch()`跟隨 HTTP 跳轉。 - `error`:如果發生跳轉,`fetch()`就報錯。 - `manual`:`fetch()`不跟隨 HTTP 跳轉,但是`response.url`屬性會指向新的 URL,`response.redirected`屬性會變為`true`,由開發者自己決定后續如何處理跳轉。 **integrity** `integrity`屬性指定一個哈希值,用于檢查 HTTP 回應傳回的數據是否等于這個預先設定的哈希值。 比如,下載文件時,檢查文件的 SHA-256 哈希值是否相符,確保沒有被篡改。 ```javascript fetch('http://site.com/file', { integrity: 'sha256-abcdef' }); ``` **referrer** `referrer`屬性用于設定`fetch()`請求的`referer`標頭。 這個屬性可以為任意字符串,也可以設為空字符串(即不發送`referer`標頭)。 ```javascript fetch('/page', { referrer: '' }); ``` **referrerPolicy** `referrerPolicy`屬性用于設定`Referer`標頭的規則。可能的取值如下: - `no-referrer-when-downgrade`:默認值,總是發送`Referer`標頭,除非從 HTTPS 頁面請求 HTTP 資源時不發送。 - `no-referrer`:不發送`Referer`標頭。 - `origin`:`Referer`標頭只包含域名,不包含完整的路徑。 - `origin-when-cross-origin`:同源請求`Referer`標頭包含完整的路徑,跨域請求只包含域名。 - `same-origin`:跨域請求不發送`Referer`,同源請求發送。 - `strict-origin`:`Referer`標頭只包含域名,HTTPS 頁面請求 HTTP 資源時不發送`Referer`標頭。 - `strict-origin-when-cross-origin`:同源請求時`Referer`標頭包含完整路徑,跨域請求時只包含域名,HTTPS 頁面請求 HTTP 資源時不發送該標頭。 - `unsafe-url`:不管什么情況,總是發送`Referer`標頭。 ## 取消`fetch()`請求 `fetch()`請求發送以后,如果中途想要取消,需要使用`AbortController`對象。 ```javascript let controller = new AbortController(); let signal = controller.signal; fetch(url, { signal: controller.signal }); signal.addEventListener('abort', () => console.log('abort!') ); controller.abort(); // 取消 console.log(signal.aborted); // true ``` 上面示例中,首先新建 AbortController 實例,然后發送`fetch()`請求,配置對象的`signal`屬性必須指定接收 AbortController 實例發送的信號`controller.signal`。 `controller.abort()`方法用于發出取消信號。這時會觸發`abort`事件,這個事件可以監聽,也可以通過`controller.signal.aborted`屬性判斷取消信號是否已經發出。 下面是一個1秒后自動取消請求的例子。 ```javascript let controller = new AbortController(); setTimeout(() => controller.abort(), 1000); try { let response = await fetch('/long-operation', { signal: controller.signal }); } catch(err) { if (err.name == 'AbortError') { console.log('Aborted!'); } else { throw err; } } ``` ## 參考鏈接 - [Network requests: Fetch](https://javascript.info/fetch) - [node-fetch](https://github.com/node-fetch/node-fetch) - [Introduction to fetch()](https://developers.google.com/web/updates/2015/03/introduction-to-fetch) - [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) - [Javascript Fetch API: The XMLHttpRequest evolution](https://developerhowto.com/2019/09/14/javascript-fetch-api/) - [A Guide to Faster Web App I/O and Data Operations with Streams](https://www.sitepen.com/blog/2017/10/02/a-guide-to-faster-web-app-io-and-data-operations-with-streams/)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看