GET
→ 讀取資料POST
→ 新增資料PUT / PATCH
→ 修改資料DELETE
→ 刪除資料例子:
GET /api/users → 取得所有用戶
GET /api/users/1 → 取得 ID=1 的用戶
POST /api/users → 新增用戶
PUT /api/users/1 → 更新 ID=1 的用戶
DELETE /api/users/1 → 刪除 ID=1 的用戶
200 OK
→ 請求成功201 Created
→ 新增成功400 Bad Request
→ 請求錯誤401 Unauthorized
→ 未授權404 Not Found
→ 資源不存在500 Internal Server Error
→ 伺服器錯誤// GET 請求
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// POST 請求
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: '新文章',
body: '這是一篇練習文章',
userId: 1
})
})
.then(res => res.json())
.then(data => console.log('新增成功:', data))
.catch(err => console.error(err));
// 使用 Axios 發送 GET 請求
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => console.log(res.data))
.catch(err => console.error(err));
// 使用 Axios 發送 POST 請求
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: '新文章',
body: '這是一篇練習文章',
userId: 1
})
.then(res => console.log('新增成功:', res.data))
.catch(err => console.error(err));
建立一個簡單的文章清單 App,功能包含:
專案結構:
api-practice/
├── index.html
├── style.css
└── script.js
index.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>API 練習器</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>文章清單</h1>
<ul id="postList"></ul>
<h2>新增文章</h2>
<input type="text" id="title" placeholder="標題">
<input type="text" id="body" placeholder="內容">
<button id="addPost">新增文章</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="script.js"></script>
</body>
</html>
script.js
const postList = document.getElementById('postList');
const addBtn = document.getElementById('addPost');
const titleInput = document.getElementById('title');
const bodyInput = document.getElementById('body');
// API 來源
const API_URL = 'https://jsonplaceholder.typicode.com/posts';
// 顯示所有文章
function fetchPosts() {
axios.get(API_URL)
.then(res => {
postList.innerHTML = '';
res.data.slice(0, 5).forEach(post => { // 只顯示前5篇
const li = document.createElement('li');
li.innerHTML = `
<strong>${post.title}</strong> - ${post.body}
<button onclick="deletePost(${post.id})">刪除</button>
`;
postList.appendChild(li);
});
})
.catch(err => console.error(err));
}
// 新增文章
addBtn.addEventListener('click', () => {
const newPost = {
title: titleInput.value,
body: bodyInput.value,
userId: 1
};
axios.post(API_URL, newPost)
.then(res => {
alert('新增成功!');
fetchPosts();
})
.catch(err => console.error(err));
});
// 刪除文章
function deletePost(id) {
axios.delete(`${API_URL}/${id}`)
.then(() => {
alert(`刪除成功 (ID=${id})`);
fetchPosts();
})
.catch(err => console.error(err));
}
// 初始化
fetchPosts();