fetch與xhr的對比


㈠fetch的簡單介紹

fetch是一種HTTP數據請求的方式,是XMLHttpRequest的一種替代方案。

fetch不是ajax的進一步封裝,而是原生js。

Fetch函數就是原生js,沒有使用XMLHttpRequest對象。

 

㈡XMLHttpRequest   API  的缺點

⑴ 不符合關注分離(Separation of Concerns)的原則

⑵ 配置和調用方式非常混亂

⑶ 基於事件的異步模型寫起來也沒有現代的 Promise,generator/yield,async/await 友好。

 

⑷具體示例:

var xhr = new XMLHttpRequest(); xhr.open('GET',url); xhr.responseType = 'json'; xhr.onload = function(){     console.log(xhr.response); } xhr.onerror = function(){     console.log('xhr error'); } xhr.send();

 

㈢Fetch 的出現就是為了解決 XHR 的問題

⑴使用fetch做請求后:

fetch(url).then(function(response){     return response.json(); }).then(function(data){     console.log(data); }).catch(function(e){     console.log('error' + e); });

 

⑵es6寫法:

fetch(url).then(response=>response.json()) .then(data=>console.log(data)) .catch(e=>console.log('error' + e));

 

⑶處理text/html響應:

fetch(url).then(response=>response.text()) .then(data=>console.log(data)) .catch(e=>console.log('error' + e));

 

⑷獲取頭信息:

fetch(url).then((response)=>{     console.log(response.status);     console.log(response.statusText);     console.log(response.headers.get('Content-Type'));     console.log(response.headers.get('Date'));     return response.json(); }).then(data=>console.log(data))   .catch(e=>console.log('error' + e);

 

⑸設置頭信息

fetch(url,{     headers:{         'Accept': 'application/json',         'Content-Type': 'application/json'     } }).then(response=>response.json())   .then(data=>console.log(data))   .catch(e=>console.log('error' + e);

 

⑹提交表單

fetch(url,{     method: 'post',     body: new FormData(document.getElementById('form')) }).then(response=>response.json())   .then(data=>console.log(data))   .catch(e=>console.log('error' + e);

 

⑺提交json數據

fetch(url,{     method: 'post',     body: JSON.stringify({         username: document.getElementById('username').value,         password: document.getElementById('password').value     }) }).then(response=>response.json())   .then(data=>console.log(data))   .catch(e=>console.log('error' + e);

 

⑻fetch跨域的處理

fetch中可以設置mode為"no-cors"(不跨域)

fetch('/users.json', { method: 'post', mode: 'no-cors', data: {} }).then(function() { /* handle response */ });

 

這樣之后我們會得到一個type為“opaque”的返回。

需要指出的是,這個請求是真正抵達過后台的,

所以我們可以使用這種方法來進行信息上報,在我們之前的image.src方法中多出了一種選擇,

另外,我們在network中可以看到這個請求后台設置跨域頭之后的實際返回,有助於我們提前調試接口(當然,通過chrome插件我們也可以做的到)。

 

㈣Fetch 優點

⑴語法簡潔,更加語義化

⑵基於標准 Promise 實現,支持 async/await

⑶同構方便,使用 isomorphic-fetch

 

㈤Fetch 的兼容問題:

⒈fetch原生支持性不高,引入下面這些 polyfill 后可以完美支持 IE8+ :

⑴由於 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham

⑵引入 Promise[z1]  的 polyfill: es6-promise

⑶引入 fetch 探測庫:fetch-detector

⑷引入 fetch 的 polyfill: fetch-ie8

⑸可選:如果你還使用了 jsonp,引入 fetch-jsonp

⑹可選:開啟 Babel 的 runtime 模式,現在就使用 async/await

⒉示例:

使用isomorphic-fetch,兼容Node.js和瀏覽器兩種環境運行。

npm install --save isomorphic-fetch es6-promise require('es6-promise').polyfill(); require('isomorphic-fetch');

 

參考:https://blog.csdn.net/kezanxie3494/article/details/102956869


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM