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服务器错误
动手练习
- 完成上面的 Todo API,用 curl 或 Postman 测通全部 5 个接口。
- 加输入校验:title 超过 100 字返回 400;id 不是数字返回 400。
- 把数据从内存数组换成 JSON 文件持久化(
fs/promises读写),为下一课接数据库做准备。