这篇会分别使用前面几篇文章介绍的:XHR、Promise、fetch、async、axios 等 5 种方法取得同样的资料,也写了各种 API 串接捕捉错误的方式,如果有写错拜托告诉我 ><
使用的 API:RANDOM USER GENERATOR
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);
};
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);
});
const url = fetch("https://randomuser.me/api/?results")
.then(response => response.json())
.then(results => console.log(results))
.catch(err => console.log(err));
async 会需要用到的错误处理语法在 Day 25 - Exception Handling
(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
.get("https://randomuser.me/api/?results")
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
使用前面五种方式皆能成功获得 response 的资料,response.data 里有 info,results
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
这篇会来教大家如何透过 Firebase 在你的 iOS App 上实作注册以及登入功能 透过 Fi...
共变数covariance 共变数是用来衡量两个变数变动的方向及程度。若两变数分别X跟Y,如果X的变...
在上一篇我们下载完了准备工具後 这篇我们要来开始架设我们的程序环境了 这一篇我们会教大家 如何下载P...
之前在贪婪演算法的文章中有提到,现实生活中并不是所有问题都能用演算法快狠准地解决,有些困难的问题只有...
昨天我们已经能成功将JSON格式的资料print出来了,接着就来实作天气预报App吧! 首先,我们要...