timmy 修订了这个 Gist 6 months ago. 转到此修订
没有任何变更
timmy 修订了这个 Gist 6 months ago. 转到此修订
2 files changed, 31 insertions
async_fetch_example.js(文件已创建)
| @@ -0,0 +1,16 @@ | |||
| 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 裡 | |
fetch_api_example.js(文件已创建)
| @@ -0,0 +1,15 @@ | |||
| 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 | + | }); | |
上一页
下一页