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); // [email protected]
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#14 注册与按钮

>>:  [iT铁人赛Day29]练习题(8)

【在 iOS 开发路上的大小事-Day15】透过 Firebase 来管理使用者 (Sign in with E-mail 篇) Part1

这篇会来教大家如何透过 Firebase 在你的 iOS App 上实作注册以及登入功能 透过 Fi...

DAY24-EXCEL统计分析:共变数介绍

共变数covariance 共变数是用来衡量两个变数变动的方向及程度。若两变数分别X跟Y,如果X的变...

[Day 3]开胃沙拉-Python安装及Vagrant虚拟环境架设

在上一篇我们下载完了准备工具後 这篇我们要来开始架设我们的程序环境了 这一篇我们会教大家 如何下载P...

Day 26:旅行推销员问题(TSP)

之前在贪婪演算法的文章中有提到,现实生活中并不是所有问题都能用演算法快狠准地解决,有些困难的问题只有...

【从零开始的Swift开发心路历程-Day23】天气预报App实作Part2

昨天我们已经能成功将JSON格式的资料print出来了,接着就来实作天气预报App吧! 首先,我们要...