一个完整的请求过程
使用JSON Server
首先安装 JSON Server:
npm install -g json-server
创建 db.json 文件并启动服务器:
json-server --watch db.json
JSON Server 会:
读取 db.json 文件
创建一个 HTTP 服务器(默认在 3000 端口)
为文件中的每个顶级属性(users, posts, comments)自动创建对应的 RESTful 路由
// JSON Server 会自动创建以下路由:
GET /users // 获取所有用户
GET /users/1 // 获取指定 ID 的用户
POST /users // 创建新用户
PUT /users/1 // 更新指定用户
DELETE /users/1 // 删除指定用户
GET /posts // 获取所有文章
GET /comments // 获取所有评论
{
"users": [
{
"name": "张三",
"age": 26,
"id": "1"
},
{
"id": "c1da",
"name": "王五",
"age": 28
},
{
"id": "1740",
"name": "111",
"age": "3"
},
{
"id": "9c99",
"name": "124",
"age": "12"
},
{
"id": "7d44",
"name": "王五",
"age": 28
}
],
"posts": [
{
"id": "1",
"title": "第一篇文章",
"author": "张三",
"userId": 1
},
{
"id": "2",
"title": "第二篇文章",
"author": "李四",
"userId": 2
}
],
"comments": [
{
"id": "1",
"body": "很棒的文章!",
"postId": 1
},
{
"id": "2",
"body": "学习了!",
"postId": 1
}
]
}
demo.js
// 2. 前端代码
// 基础配置
const API_BASE_URL = "http://localhost:3000";
// 封装请求方法
const request = {
// GET 请求
get: (url) => {
return fetch(${API_BASE_URL}${url}
)
.then((response) => response.json())
.catch((error) => console.error("Error:", error));
},
// POST 请求
post: (url, data) => {
return fetch(${API_BASE_URL}${url}
, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error));
},
// PUT 请求
put: (url, data) => {
return fetch(${API_BASE_URL}${url}
, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error));
},
// DELETE 请求
delete: (url) => {
return fetch(${API_BASE_URL}${url}
, {
method: "DELETE",
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error));
},
};
// 使用示例
async function demo() {
try {
// 1. 获取所有用户
console.log("获取所有用户:");
const users = await request.get("/users");
console.log(users);
// 2. 获取特定用户
console.log("获取 ID 为 1 的用户:");
const user = await request.get("/users/1");
console.log(user);// 3. 创建新用户
console.log("创建新用户:");
const newUser = await request.post("/users", {name: "王五",age: 28,
});
console.log(newUser);// 4. 更新用户
console.log("更新用户信息:");
const updatedUser = await request.put("/users/1", {name: "张三",age: 26,
});
console.log(updatedUser);// 5. 删除用户
console.log("删除用户:");
await request.delete("/users/2");
console.log("用户已删除");// 6. 获取用户的文章
console.log("获取用户的文章:");
const userPosts = await request.get("/posts?userId=1");
console.log(userPosts);// 7. 获取文章的评论
console.log("获取文章的评论:");
const postComments = await request.get("/comments?postId=1");
console.log(postComments);
} catch (error) {
console.error("操作失败:", error);
}
}
// 执行示例
demo();
// 添加 DOM 操作
document.addEventListener("DOMContentLoaded", () => {
// 获取并显示用户列表
function loadUsers() {
request.get("/users").then((users) => {
const userList = document.getElementById("users");
userList.innerHTML = users
.map(
(user) => <li> ${user.name} (${user.age}岁) <button onclick="deleteUser(${user.id})">删除</button> </li>
)
.join("");
});
}
// 获取并显示文章列表
function loadPosts() {
request.get("/posts").then((posts) => {
const postList = document.getElementById("posts");
postList.innerHTML = posts
.map(
(post) => <li> <h3>${post.title}</h3> <p>作者:${post.author}</p> </li>
)
.join("");
});
}
// 添加用户
document.getElementById("userForm").addEventListener("submit", (e) => {
e.preventDefault();
const name = document.getElementById("name").value;
const age = document.getElementById("age").value;
request.post("/users", { name, age }).then(() => {loadUsers();document.getElementById("userForm").reset();
});
});
// 删除用户
window.deleteUser = (id) => {
request.delete(/users/${id}
).then(() => loadUsers());
};
// 初始加载用户列表和文章列表
loadUsers();
loadPosts();
});
index.html
用户管理系统
<div id="userList"><h2>用户列表</h2><ul id="users"></ul>
</div><div id="postList"><h2>文章列表</h2><ul id="posts"></ul>
</div><div id="addUser"><h2>添加用户</h2><form id="userForm"><input type="text" id="name" placeholder="姓名" /><input type="number" id="age" placeholder="年龄" /><button type="submit">添加</button></form>
</div><script src="demo.js"></script>