# Fetch API (ES6) ###### tags: `Javascript` 為一種遠端傳接資料的方法。 * 原生js : ajax get ``` // 宣告一個 XHR 的物件 var Req = new XMLHttpRequest(); // 定義連線方式 Req.open('get', 'https://randomuser.me/api/', true); // 送出請求 Req.send(); // 如果成功就執行 onload() Req.onload = ()=>{ const data = JSON.parse(this.responseText); } ``` * JQuery ``` $.ajax({ url: 'https://randomuser.me/api/', dataType: 'json', success: function(data) { console.log(data); // 取得的遠端資料 } }); ``` * Fetch 1. 以Promise 做回應(詳見 ['Promise'](https://hackmd.io/HrHdFhdOTKeWVVbQLm3NbA) ) 2. 回傳 : ReadableStream 物件 需要使用不同資料類型使用對應方法,才能正確取得資料物件。 > ReadableStream 物件 透過以下方法取得資料 1. arrayBuffer() 2. blob() 3. formData() 4. json() 5. text() > Fetch GET ``` fetch('https://randomuser.me/api/', {}) .then((response) => { // 這裡會得到一個 ReadableStream 的物件 console.log(response); // 可以透過 blob(), json(), text() 轉成可用的資訊 return response.json(); }).then((jsonData) => { console.log(jsonData); }).catch((err) => { console.log('錯誤:', err); }); /* then : 將上一步ㄉ回傳值作為參數傳入下一步。Promise的特性。 catch : 錯誤回應 (404, 500…) */ ``` > Fetch POST ``` let url = 'https://hexschool-tutorial.herokuapp.com/api/signup'; fetch(url, { method: 'POST', // headers 加入 json 格式 headers: { 'Content-Type': 'application/json' }, // body 將 json 轉字串送出 body: JSON.stringify({ email: 'lovef1232e@hexschool.com', password: '12345678' }) }).then((response) => { return response.json(); }).then((jsonData) => { console.log(jsonData); }).catch((err) => { console.log('錯誤:', err); }) ```