JavaScript Fetch API 教學
🔹 1. 基本語法
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("錯誤:", error));🔹 2. GET 請求
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => res.json())
.then(data => console.log(data));🔹 3. POST 請求
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Hello",
body: "This is a test",
userId: 1
})
})
.then(res => res.json())
.then(data => console.log(data));🔹 4. PUT 與 DELETE 請求
PUT(更新整筆資料)
DELETE(刪除資料)
🔹 5. async/await 寫法
🔹 6. 常見錯誤處理
Last updated