1. 程式人生 > 實用技巧 >fetch的用法

fetch的用法

fetch是web提供的一個可以獲取非同步資源的api,目前還沒有被所有瀏覽器支援,它提供的api返回的是Promise物件,所以你在瞭解這個api前首先得了解Promise的用法。參考阮老師的文章

那我們首先講講在沒有fetch的時候,我們是如何獲取非同步資源的:

//傳送一個get請求是這樣的:

//首先例項化一個XMLHttpRequest物件
var httpRequest = new XMLHttpRequest();

//註冊httpRequest.readyState改變時會回撥的函式,httpRequest.
//readyState共有5個可能的值,
//0    UNSENT (未開啟)    open()方法還未被呼叫;
//1 OPENED (未傳送) send()方法還未被呼叫; //2 HEADERS_RECEIVED (已獲取響應頭) send()方法已經被呼叫, 響應頭和響應狀態已經返回; //3 LOADING (正在下載響應體) 響應體下載中; responseText中已經獲取了部分資料; //4 DONE (請求完成) 整個請求過程已經完畢. httpRequest.onreadystatechange = function(){ //該回調函式會被依次呼叫4次 console.log(httpRequest.readyState); if(httpRequest.readyState===4){
//請求已完成 if(httpRequest.status===200){ //http狀態為200 console.log(httpRequest.response); var data = JSON.parse(httpRequest.response); console.log(data); } } } //請求的網址 var url = "http://127.0.0.1:7777/list"; //該方法為初始化請求,第一個引數是請求的方法,比如GET,POST,PUT,第二個引數是請求的url httpRequest.open('GET',url,true
); //設定http請求頭 httpRequest.setRequestHeader("Content-Type","application/json"); //發出請求,引數為要傳送的body體,如果是GET方法的話,一般無需傳送body,設為空就可以 httpRequest.send(null); 關於XMLHttpRequest的更多用法請參照:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest#open() 如果用了fetch之後,傳送一個get請求是這樣的: //請求的網址 var url = "http://127.0.0.1:7777/list"; //發起get請求 var promise = fetch(url).then(function(response) { //response.status表示響應的http狀態碼 if(response.status === 200){ //json是返回的response提供的一個方法,會把返回的json字串反序列化成物件,也被包裝成一個Promise了 return response.json(); }else{ return {} } }); promise = promise.then(function(data){ //響應的內容 console.log(data); }).catch(function(err){ console.log(err); }) 接下來介紹下fetch的語法: /** 引數: input:定義要獲取的資源。可能的值是:一個URL或者一個Request物件。 init:可選,是一個物件,引數有: method: 請求使用的方法,如 GET、POST。 headers: 請求的頭資訊,形式為 Headers 物件或 ByteString。 body: 請求的 body 資訊:可能是一個 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 物件。注意 GET 或 HEAD 方法的請求不能包含 body 資訊。 mode: 請求的模式,如 cors、 no-cors 或者 same-origin,預設為no-cors,該模式允許來自 CDN 的指令碼、其他域的圖片和其他一些跨域資源,但是首先有個前提條件,就是請求的 method 只能是HEAD、GET 或 POST。此外,如果 ServiceWorkers 攔截了這些請求,它不能隨意新增或者修改除這些之外 Header 屬性。第三,JS 不能訪問 Response 物件中的任何屬性,這確保了跨域時 ServiceWorkers 的安全和隱私資訊洩漏問題。cors模式允許跨域請求,same-origin模式對於跨域的請求,將返回一個 error,這樣確保所有的請求遵守同源策略。 credentials: 請求的 credentials,如 omit、same-origin 或者 include。 cache: 請求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached. 返回值:一個 Promise,resolve 時回傳 Response 物件。 */ fetch(input, init).then(function(response) { }); 一個傳送post請求的示例: fetch("http://127.0.0.1:7777/postContent", { method: "POST", headers: { "Content-Type": "application/json", }, mode: "cors", body: JSON.stringify({ content: "留言內容" }) }).then(function(res) { if (res.status === 200) { return res.json() } else { return Promise.reject(res.json()) } }).then(function(data) { console.log(data); }).catch(function(err) { console.log(err); });