Utoljára aktív 6 months ago

此 JavaScript 程式碼示範了如何使用 fetch API 以非同步方式抓取資料,並處理回應與錯誤,適用於從指定的 API 端點獲取資料。

Revízió 79ab02c87e97022da38087ed587ee985da0d7737

async_fetch_example.js Eredeti
1async 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// 執行函式
16fetchExampleData(); // 記得這要在 async 環境下跑,比如在 async function 或 script 裡
17
fetch_api_example.js Eredeti
1fetch('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