前端最小必备(零基础详细版)

目标:写出一个含表单的静态页面,能用 fetch/axios 发送 JSON 请求并展示响应,为后端练习提供最小前端能力。

← 返回一级入口

学习目标与前置

建议用时:60 分钟准备:任意浏览器,静态服务器或直接 file://

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:本地打开与运行

# Python 3 自带
python -m http.server 8000
# 或 VSCode Live Server 插件

浏览器访问 http://localhost:8000

Step 3:理解 fetch 配置

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:跨域初识

课堂练习

课后巩固

教学提示