CodeRoadMap
路线图学习路径文章题库资源社区

浏览

首页路线图学习路径知识库题库文章资源社区我的学习
CodeRoadMap

中文编程学习导航:路线图、讲义与题库,进度可同步。

路线图学习路径文章题库社区

© 2026 CodeRoadMap

津ICP备2026012044号-1|coderoadmap@126.com
首页/全栈 Web 开发/Node.js 与 API

课程目录

  1. 01HTML & CSS 基础
  2. 02JavaScript 核心
  3. 03JavaScript 练习
  4. 04React 入门
  5. 05React 项目
  6. 06Node.js 与 API
  7. 07数据库
  8. 08全栈毕业项目
第 06 课

Node.js 与 API

Express、REST、中间件与错误处理。

课程内容

Node.js 与 API

Node.js 让 JavaScript 跑出浏览器、跑在服务器上。本课用 Express 框架构建 REST API,这是全栈开发的后端基本功。

学习目标

  • 理解 REST API 的设计规范
  • 用 Express 实现路由、中间件、错误处理
  • 掌握请求/响应的完整生命周期

快速开始

mkdir todo-api && cd todo-api
npm init -y
npm install express
// server.js
const express = require("express");
const app = express();

app.use(express.json()); // 解析 JSON 请求体的中间件

app.get("/api/todos", (req, res) => {
  res.json([{ id: 1, title: "学 Express", done: false }]);
});

app.listen(3000, () => console.log("服务运行在 http://localhost:3000"));

REST 路由设计

资源用名词复数,动作用 HTTP 方法表达:

方法路径含义
GET/api/todos获取列表
GET/api/todos/:id获取单个
POST/api/todos新建
PUT/api/todos/:id整体更新
DELETE/api/todos/:id删除
let todos = [];
let nextId = 1;

app.post("/api/todos", (req, res) => {
  const { title } = req.body;
  if (!title) {
    return res.status(400).json({ error: "title 不能为空" });
  }
  const todo = { id: nextId++, title, done: false };
  todos.push(todo);
  res.status(201).json(todo); // 201 = Created
});

app.delete("/api/todos/:id", (req, res) => {
  const id = Number(req.params.id);
  const idx = todos.findIndex(t => t.id === id);
  if (idx === -1) {
    return res.status(404).json({ error: "不存在" });
  }
  todos.splice(idx, 1);
  res.status(204).end(); // 204 = No Content
});

中间件

中间件是请求处理的流水线,next() 交给下一个:

// 日志中间件:每个请求都会经过
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// 错误处理中间件(4 个参数,放在所有路由之后)
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "服务器内部错误" });
});

状态码约定

  • 200 成功 / 201 创建成功 / 204 成功但无返回体
  • 400 请求参数错误 / 401 未登录 / 403 无权限 / 404 不存在
  • 500 服务器错误

动手练习

  1. 完成上面的 Todo API,用 curl 或 Postman 测通全部 5 个接口。
  2. 加输入校验:title 超过 100 字返回 400;id 不是数字返回 400。
  3. 把数据从内存数组换成 JSON 文件持久化(fs/promises 读写),为下一课接数据库做准备。

参考资源

  • Express 官方中文文档
  • The Odin Project — Node.js 课程
  • REST API 设计最佳实践

观看视频课程

https://www.theodinproject.com/paths/foundations/courses/foundations

← 上一课React 项目下一课 →数据库