fetch是一種替代XMLHttpRequest的網絡請求API,它提供了一個簡單、靈活並且具有強大功能的接口。在本文中,我們將從多個方面詳細闡述fetch請求的相關知識。
一、fetch請求攔截
fetch請求可以通過攔截器來實現請求的攔截,可以在請求即將發送和響應已經獲取之前攔截請求。攔截器可以幫助我們在請求發送之前更改請求參數、在請求結束之後處理響應結果。
以下是一個fetch請求攔截的示例代碼:
fetch('/api/user', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); function interceptor(fetchFunc) { return (url, options) => { console.log(`Intercepting request to ${url} with options`, options); return fetchFunc(url, options) .then(response => { console.log(`Intercepting response from ${url} with response`, response); return response; }) .catch(error => { console.error(`Intercepting error from ${url} with error`, error); throw error; }); }; } fetch = interceptor(fetch);
在上面的代碼中,我們定義了一個攔截器函數interceptor,並通過interceptor函數來對fetch方法進行攔截。在攔截器中,我們可以通過console.log方法來打印請求和響應內容。最後通過將攔截器函數返回後fetch方法調用指向了攔截器。
二、fetch請求攜帶cookie
默認情況下,fetch請求不會攜帶cookie信息。在需要攜帶cookie的請求中,我們需要在請求頭中設置參數credentials為include。
以下是一個fetch請求攜帶cookie的示例代碼:
fetch('/api/user', { method: 'GET', credentials: 'include', headers: { 'Content-Type': 'application/json', } }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
在上面的代碼中,我們通過設置credentials為include來攜帶cookie信息,同時也設置了請求頭的Content-Type參數。
三、fetch請求如何中斷
fetch請求使用Promise實現,若需要中斷請求可以通過AbortController來實現。
以下是一個fetch請求中斷的示例代碼:
const controller = new AbortController(); const signal = controller.signal; fetch('/api/user', { method: 'GET', signal: signal, headers: { 'Content-Type': 'application/json', } }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); // 中斷請求 controller.abort();
在上面的代碼中,我們使用AbortController來實現請求的中斷,通過定義controller.signal並將其作為fetch請求的參數傳入來實現中斷。
四、fetch請求和ajax的區別
fetch請求與ajax有很多相似之處,但是也有不同之處:
- fetch請求使用Promise實現,ajax使用回調函數實現;
- fetch請求默認不攜帶cookie信息,ajax默認攜帶cookie信息;
- fetch請求支持跨域頭,ajax需要使用jsonp實現跨域;
- fetch請求使用可讀流處理文件,ajax不能直接處理文件;
- fetch請求使用狀態碼標記響應狀態,ajax使用readyState和status標記響應狀態。
五、fetch請求js文件
fetch請求可以用於獲取js文件,獲取到之後可以通過eval方法將文件內容解析為可執行的js代碼。
以下是一個fetch請求獲取js文件的示例代碼:
fetch('/api/jsfile') .then(response => response.text()) .then(data => { eval(data); });
在上面的代碼中,我們通過fetch獲取js文件,然後通過text方法將文件內容轉為字符串,最後使用eval方法將獲取到的js代碼執行。
六、fetch請求封裝
使用fetch的時候,我們經常會發現fetch的api操作沒法滿足我們的要求,比如fetch需要不同的headers、需要不同的parse方式等等,如果在業務代碼中重複的使用fetch會讓代碼顯得冗餘,不夠優雅。我們可以通過封裝fetch,將複雜邏輯統一處理,讓代碼更為簡潔優雅。
以下是一個fetch請求封裝的示例代碼:
const http = { get: (url, data, headers) => { return http.request(url, 'GET', data, headers); }, post: (url, data, headers) => { return http.request(url, 'POST', data, headers); }, request: async (url, method, data, headers) => { try { const response = await fetch(url, { method: method.toUpperCase(), headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(data) }); const json = await response.json(); return json; } catch(error) { console.error(error); } } }; http.get('/api/user', {}, {'Authorization': 'Bearer xxx'}) .then(data => console.log(data)) .catch(error => console.error(error));
在上面的代碼中,我們定義了一個http對象,通過http對象的get和post方法來發送get和post請求。在http.request方法中,我們對請求進行了封裝,支持自定義的headers、支持異步await等操作。
七、fetch請求跨域
fetch請求跨域需要跨域服務器設置Access-Control-Allow-Origin響應頭,設置為允許請求的源地址。另一方面,由於fetch請求默認不攜帶cookie信息, 跨域請求需要設置credentials為include才能攜帶cookie。
以下是一個fetch請求跨域的示例代碼:
fetch('http://cors-test.xxx.com/test.php', { method: 'GET', credentials: 'include', headers: { 'Content-Type': 'application/json', } }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
在上面的代碼中,我們通過fetch請求跨域服務器test.php的數據,並攜帶cookie信息。
八、fetch請求參數
fetch請求可以通過URLSearchParams來構建請求參數,也可以直接在URL中傳遞參數。
以下是一個fetch請求參數的示例代碼:
const params = new URLSearchParams(); params.append('name', 'Tom'); params.append('age', 18); fetch('/api/user?' + params, { method: 'GET', headers: { 'Content-Type': 'application/json', } }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
在上面的代碼中,我們通過URLSearchParams來構建請求參數,然後將參數拼接在URL後面來發送請求。
九、fetch請求文件流
fetch請求可以通過ReadableStream接口來處理文件流,通過response.body獲取響應的可讀流數據。
以下是一個fetch請求文件流的示例代碼:
fetch('/api/filestream') .then(response => { const reader = response.body.getReader(); return new ReadableStream({ start(controller) { function push() { reader.read().then(({ done, value }) => { if (done) { controller.close(); return; } controller.enqueue(value); push(); }); } push(); } }) }) .then(stream => new Response(stream)) .then(response => response.blob()) .then(blob => console.log(blob)) .catch(error => console.error(error));
在上面的代碼中,我們通過fetch響應的body獲取到response的可讀流,然後通過ReadableStream來將可讀流轉化為ReadableStream實例後,將其封裝為Response實例,最後通過blob方法將response響應回來的文件數據轉化為blob對象。
十、fetch請求api接口選取
根據要求,我們需要選取3~5個與fetch請求相關的api接口,以下是選取的接口:
- fetch:發起網絡請求
- Headers:請求或響應頭集合
- Response:網絡請求響應結果
- Request:網絡請求的信息,包含請求方法、請求地址及請求頭等信息
- FetchEvent:表示FetchEvent(網絡請求事件)在服務工作線程中的事件狀態
以上是fetch請求相關知識的詳細闡述,fetch作為一種新一代的網絡請求API,它具備了強大的功能並且易於使用。熟練掌握fetch的使用,有助於我們更好地進行網絡請求相關開發。希望文章對您有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/152099.html