学习目标与前置
建议用时:60 分钟准备:任意浏览器,静态服务器或直接 file://
- 理解 HTML 结构、表单元素、基础 CSS。
- 能用 fetch 发送 JSON 请求并显示 JSON 响应。
- 知道跨域的概念(细节放在安全章节)。
Step 1:编写最小页面
flowchart LR A[表单输入] --> B[JS 采集数据] B --> C[fetch/axios 发送 JSON 请求] C --> D[后端 API] D --> E[返回 JSON] E --> F[页面用 JSON.stringify 渲染]
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Todo 前端最小版</title>
<style>
body { font-family: Arial, sans-serif; max-width: 640px; margin: 24px auto; }
form { display: flex; gap: 8px; margin-bottom: 12px; }
input, button { padding: 8px; font-size: 14px; }
pre { background: #0b2545; color: #e2e8f0; padding: 10px; border-radius: 8px; }
</style>
</head>
<body>
<h2>新增待办</h2>
<form id="todoForm">
<input name="title" placeholder="待办标题" required />
<button type="submit">提交</button>
</form>
<button id="listBtn">获取列表</button>
<pre id="resp"></pre>
<script>
const respEl = document.getElementById('resp');
document.getElementById('todoForm').addEventListener('submit', async (e) => {
e.preventDefault();
const title = e.target.title.value;
const res = await fetch('http://localhost:8080/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, done: false })
});
respEl.textContent = await res.text();
});
document.getElementById('listBtn').addEventListener('click', async () => {
const res = await fetch('http://localhost:8080/api/todos');
respEl.textContent = await res.text();
});
</script>
</body>
</html>
保存为 index.html。
Step 2:本地打开与运行
- 方法 A:直接双击
index.html用浏览器打开(file://)。 - 方法 B:用静态服务器(推荐,便于跨域演示):
# Python 3 自带
python -m http.server 8000
# 或 VSCode Live Server 插件
浏览器访问 http://localhost:8000。
Step 3:理解 fetch 配置
method:HTTP 方法,POST/GET/PUT/DELETE。headers:设置 Content-Type 为application/json。body:用JSON.stringify序列化对象。- 响应:用
await res.text()或await res.json()读取。
Step 4:用 axios(可选)
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
axios.post('http://localhost:8080/api/todos', { title: 'demo', done: false })
.then(res => console.log(res.data))
.catch(err => console.error(err));
</script>
说明:axios 默认将对象转为 JSON,并自动解析 JSON 响应。
Step 5:格式化显示 JSON
function showJson(el, data) {
el.textContent = JSON.stringify(data, null, 2);
}
将 respEl.textContent = await res.text(); 换成:
const data = await res.json();
showJson(respEl, data);
Step 6:跨域初识
- 如果前端端口与后端不同(如 8000 → 8080),浏览器会发起预检(OPTIONS)。
- 若收到 CORS 错误,需要后端开启允许的 Origin/Methods/Headers(详见安全章节)。
课堂练习
- 增加“标记完成”按钮,发送 PUT /api/todos/{id},传 JSON
{done:true}。 - 将响应通过
JSON.stringify(..., null, 2)美化显示。 - 加 loading 文案:请求开始时显示“加载中...”,完成后隐藏。
课后巩固
- 用表格展示 todos 的 title/done 状态。
- 提取后端地址为常量(如
const API_BASE = 'http://localhost:8080'),便于切换本地/线上。 - 用 axios 重写 fetch 逻辑,对比差异。
教学提示
- 演示时可故意让接口 404/500,帮助学生通过 Network 面板定位问题。
- 跨域问题在后续安全章节详细展开,此处只做初识。
- 强调“最小可用前端”:核心是请求与展示,不扩展复杂布局或框架。