這篇會分別使用前面幾篇文章介紹的: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); // randy.nichols@example.com
console.log(res.data.results[0].picture.large); //https://randomuser.me/api/portraits/men/47.jpg