下面每一個都不用申請 API KEY、不用架伺服器,學員直接用瀏覽器 fetch 就能拿到即時資料。按按鈕試試,旁邊就是對應的程式碼。
async function getWeather(){
const city = document.querySelector('#wcity').value;
// 1) 先把城市名轉成經緯度
const g = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${city}&count=1&language=zh`).then(r=>r.json());
const { latitude, longitude, name } = g.results[0];
// 2) 用經緯度查即時天氣
const w = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m,relative_humidity_2m,wind_speed_10m`).then(r=>r.json());
console.log(name, w.current.temperature_2m + '°C');
}
async function getFx(){
const amt = document.querySelector('#amt').value;
const from = document.querySelector('#from').value;
const to = document.querySelector('#to').value;
const d = await fetch(`https://api.frankfurter.app/latest?amount=${amt}&from=${from}&to=${to}`).then(r=>r.json());
console.log(d.rates[to]); // 換算結果
}
// 三個都是一行搞定:
fetch('https://pokeapi.co/api/v2/pokemon/pikachu').then(r=>r.json());
fetch('https://randomuser.me/api/').then(r=>r.json());
fetch('https://dog.ceo/api/breeds/image/random').then(r=>r.json());
fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=twd')
.then(r=>r.json()).then(d=> console.log(d.bitcoin.twd));