async_fetch_example.js
· 819 B · JavaScript
原始文件
async function fetchExampleData() {
try {
const request = await fetch('https://jsonplaceholder.typicode.com/todos/1'); // 這裡用 jsonplaceholder 的 endpoint,換成你想用的 URL
if (!request.ok) { // 檢查回應狀態,確保沒問題
throw new Error(`HTTP error! Status: ${request.status}`);
}
const jsonResponse = await request.json(); // 轉換回應成 JSON
console.log('ID:', jsonResponse.id); // 印出特定欄位,比原來的 IP 換成 ID
console.log('標題:', jsonResponse.title); // 印出標題,類似原來的國家欄位
} catch (error) {
console.error('抓 API 時出問題咧:', error); // 如果有錯誤,就印出來
}
}
// 執行函式
fetchExampleData(); // 記得這要在 async 環境下跑,比如在 async function 或 script 裡
| 1 | async function fetchExampleData() { |
| 2 | try { |
| 3 | const request = await fetch('https://jsonplaceholder.typicode.com/todos/1'); // 這裡用 jsonplaceholder 的 endpoint,換成你想用的 URL |
| 4 | if (!request.ok) { // 檢查回應狀態,確保沒問題 |
| 5 | throw new Error(`HTTP error! Status: ${request.status}`); |
| 6 | } |
| 7 | const jsonResponse = await request.json(); // 轉換回應成 JSON |
| 8 | console.log('ID:', jsonResponse.id); // 印出特定欄位,比原來的 IP 換成 ID |
| 9 | console.log('標題:', jsonResponse.title); // 印出標題,類似原來的國家欄位 |
| 10 | } catch (error) { |
| 11 | console.error('抓 API 時出問題咧:', error); // 如果有錯誤,就印出來 |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | // 執行函式 |
| 16 | fetchExampleData(); // 記得這要在 async 環境下跑,比如在 async function 或 script 裡 |
| 17 |
fetch_api_example.js
· 634 B · JavaScript
原始文件
fetch('https://jsonplaceholder.typicode.com/todos/1') // 這裡換成你想抓的 API URL
.then(response => {
if (!response.ok) { // 檢查回應狀態,確保是 200 OK
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // 轉換回應成 JSON
})
.then(data => {
console.log('API 資料:', data); // 印出整個回應資料
// 例如,如果你想抓特定欄位,像 IP 和國家,可以這樣:
// console.log(data.ip, data.country);
})
.catch(error => {
console.error('抓取 API 時出問題咧:', error); // 捕捉錯誤並印出來
});
| 1 | fetch('https://jsonplaceholder.typicode.com/todos/1') // 這裡換成你想抓的 API URL |
| 2 | .then(response => { |
| 3 | if (!response.ok) { // 檢查回應狀態,確保是 200 OK |
| 4 | throw new Error(`HTTP error! Status: ${response.status}`); |
| 5 | } |
| 6 | return response.json(); // 轉換回應成 JSON |
| 7 | }) |
| 8 | .then(data => { |
| 9 | console.log('API 資料:', data); // 印出整個回應資料 |
| 10 | // 例如,如果你想抓特定欄位,像 IP 和國家,可以這樣: |
| 11 | // console.log(data.ip, data.country); |
| 12 | }) |
| 13 | .catch(error => { |
| 14 | console.error('抓取 API 時出問題咧:', error); // 捕捉錯誤並印出來 |
| 15 | }); |
| 16 |