Express RESTful API — 图书管理 CRUD

知识库
知识库文档
/tech-stacks/express/examples/Express RESTful API — 图书管理 CRUD.md

文档

Express RESTful API — 图书管理 CRUD

目标

15 分钟搭建完整的 RESTful API,包含 GET/POST/PUT/DELETE 操作,数据存内存(毕设可替换为数据库)。

完整代码

// app.js
const express = require('express');
const app = express();

app.use(express.json());

// 内存数据库
let books = [
  { id: 1, title: 'Node.js 实战', author: 'Mike Cantelon', year: 2021 },
  { id: 2, title: 'JavaScript 高级程序设计', author: 'Matt Frisbie', year: 2023 },
];
let nextId = 3;

// 中间件:请求日志
app.use((req, res, next) => {
  console.log(`[${new Date().toLocaleTimeString()}] ${req.method} ${req.url}`);
  next();
});

// GET /books — 获取所有图书(支持搜索)
app.get('/books', (req, res) => {
  const { q } = req.query;
  if (q) {
    const filtered = books.filter(b =>
      b.title.includes(q) || b.author.includes(q)
    );
    return res.json({ count: filtered.length, data: filtered });
  }
  res.json({ count: books.length, data: books });
});

// GET /books/:id — 获取单本
app.get('/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).json({ error: '图书不存在' });
  res.json(book);
});

// POST /books — 新增图书
app.post('/books', (req, res) => {
  const { title, author, year } = req.body;
  if (!title || !author) {
    return res.status(400).json({ error: '标题和作者为必填' });
  }
  const book = { id: nextId++, title, author, year: year || new Date().getFullYear() };
  books.push(book);
  res.status(201).json(book);
});

// PUT /books/:id — 更新图书
app.put('/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).json({ error: '图书不存在' });
  Object.assign(book, req.body);
  res.json(book);
});

// DELETE /books/:id — 删除图书
app.delete('/books/:id', (req, res) => {
  const index = books.findIndex(b => b.id === parseInt(req.params.id));
  if (index === -1) return res.status(404).json({ error: '图书不存在' });
  books.splice(index, 1);
  res.json({ message: '已删除' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`📚 图书 API: http://localhost:${PORT}/books`));

运行与测试

npm install express
node app.js
# 测试命令(另开终端)
curl http://localhost:3000/books                    # 获取全部
curl http://localhost:3000/books/1                  # 单本
curl -X POST http://localhost:3000/books \
  -H "Content-Type: application/json" \
  -d '{"title":"Go语言编程","author":"许式伟"}'      # 新增
curl -X PUT http://localhost:3000/books/1 \
  -H "Content-Type: application/json" \
  -d '{"year":2024}'                                 # 更新
curl -X DELETE http://localhost:3000/books/1         # 删除
curl "http://localhost:3000/books?q=Node"            # 搜索

预期输出

// GET /books
{"count":2,"data":[{"id":1,"title":"Node.js 实战",...},{"id":2,...}]}
// POST /books → 201 Created
{"id":3,"title":"Go语言编程","author":"许式伟","year":2024}

信息

路径
/tech-stacks/express/examples/Express RESTful API — 图书管理 CRUD.md
更新时间
2026/5/30