JS 趴趴走 - ES6 Fetch 應用

前言

最近參加了六角的js學徒特訓班,剛好需要抓取遠端資料,之前有嘗試過XMLHttpRequest和框架axios,這次來試試看如果使用Fetch是要怎麼抓取資料

Fetch

FetchXMLHttpRequest一樣都是用來存取伺服器端的資料,以往使用XMLHttpRequest時會發現步驟很多

1
2
3
4
5
6
7
8
9
10
// 宣告一個XMLHttpRequest物件
var xhr = new XMLHttpRequest();
// 定義連線方式
xhr.open('get', '網址', true);
// 送出請求
xhr.send();
// 如果成功就執行
xhr.onload=()=>console.log(xhr.responseText);
// 失敗就 xhrError()
xhr.onerror=(err)=> console.log(err);

而Fetch就大大減少這些步驟,使用Promise的方式抓取資料,借用六角學院的api(感謝六角學院提供練習XD)

1
2
3
4
5
6
7
8
fetch('https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json')
.then((res)=> {
console.log(res.json());
return res.json(); //透過json()方法獲取資訊
})
.then((err)=> {
console.log(err);
});

我們返回了res.json()獲取資料後,此時的資料得到的是promise對象,而我們所要的值就在PromiseValue裡面

1
2
[[PromiseStatus]]: "fulfilled" //實現(fulfilled):表示操作成功完成。
[[PromiseValue]]: Array(221)

在Promise的文件中,[[PromiseValue]]是個內部變量,外部無法得到,只能在then中獲取。所以需要第二次的then來接收

1
2
3
4
5
6
7
8
9
const url='https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json';
fetch(url)
.then((res)=>{
return res.json(); //返回的的資料會傳到下一個then
}).then((data)=>{
console.log(data);
}).catch(err=>{
console.log(err);
})

最後記得要加上catch(失敗導向)

結論

使用Fetch過後,真的比以往的XMLHttpRequest或jQuery AJAX來的簡潔,認為跟框架的axios有一點像;這次剛好只碰到GET,以後看有沒有機會學習到其他方法~


參考文獻

ES6 Fetch 遠端資料方法
結合promise對原生fetch的兩個then用法理解
JavaScript Fetch API 使用教學