iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
自我挑戰組

Be friend with JavaScript系列 第 28

Day 28 - 使用各種方式取得資料

這篇會分別使用前面幾篇文章介紹的:XHR、Promise、fetch、async、axios 等 5 種方法取得同樣的資料,也寫了各種 API 串接捕捉錯誤的方式,如果有寫錯拜託告訴我 ><

使用的 API:RANDOM USER GENERATOR

  • XMLHttpRequest

Day 22 - Ajax

const url = "https://randomuser.me/api/?results";
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send(null);
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 400) {
    console.log(JSON.parse(xhr.response));
  }
};
xhr.onerror = function () {
    console.log(xhr.statusText);
};
  • Promise

Day 23 - Promise

function get(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.send(null);
    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 400) {
        resolve(JSON.parse(xhr.response));
      }
    };
    xhr.onerror = function () {
      reject(xhr.statusText);
    };
  });
}
get("https://randomuser.me/api/?results")
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.error(err);
  });
  • fetch

Day 24 - fetch

const url = fetch("https://randomuser.me/api/?results")
  .then(response => response.json())
  .then(results => console.log(results))
  .catch(err => console.log(err));
  • async

async 會需要用到的錯誤處理語法在 Day 25 - Exception Handling

Day 26 - async / await

(async function getData() {
    try{
        let res = await axios.get('https://randomuser.me/api/?results=1');
        let data = res.data;
        console.log(data);
    }catch(err){
        console.log(err);
    }
})()

or

(async function getData() {
  try {
    let res = await fetch("https://randomuser.me/api/?results=1");
    let data = await res.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
})()
  • axios

Day 27 - axios

axios
  .get("https://randomuser.me/api/?results")
  .then(res => {
    console.log(res.data);
  })
  .catch(err => console.log(err));

使用前面五種方式皆能成功獲得 response 的資料,response.data 裡有 info,results
https://ithelp.ithome.com.tw/upload/images/20210929/20140282YPuovmFk7k.jpg
results 裡面才有隨機人物的資料

console.log(res.data); // {results: Array(1), info: {…}}
console.log(res.data.results[0].name); // {title: 'Mr', first: 'Randy', last: 'Nichols'}
console.log(res.data.results[0].cell); // 0460-461-109
console.log(res.data.results[0].email); // randy.nichols@example.com
console.log(res.data.results[0].picture.large); //https://randomuser.me/api/portraits/men/47.jpg

https://ithelp.ithome.com.tw/upload/images/20210929/20140282diuIySDi74.jpg


上一篇
Day 27 - axios
下一篇
Day 29 - Math Object & Date Object
系列文
Be friend with JavaScript39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言