手把手教你用 Node.js + MongoDB 搭建 RESTful API 服务

🧭 一、项目背景与技术选型

🧩 场景说明:

本项目模拟一个博客系统后端接口,具备以下功能:

  • 用户注册、登录(JWT 鉴权)
  • 文章增删改查
  • 评论系统
  • 基础的权限控制

🔧 技术选型:

模块 技术
语言 Node.js (v18+)
框架 Express
数据库 MongoDB(使用 mongoose ODM)
身份认证 JWT
接口测试 Postman

🧱 二、项目结构预览

lua 复制代码
lua
复制编辑
blog-api/
├── app.js
├── config/
│   └── db.js
├── controllers/
│   ├── auth.js
│   ├── posts.js
├── models/
│   ├── user.js
│   ├── post.js
├── routes/
│   ├── auth.js
│   ├── posts.js
├── middlewares/
│   └── auth.js
└── package.json

⚙️ 三、环境准备与初始化

bash 复制代码
bash
复制编辑
mkdir blog-api && cd blog-api
npm init -y
npm install express mongoose bcryptjs jsonwebtoken dotenv cors
npm install --save-dev nodemon

.env 配置:

ini 复制代码
ini
复制编辑
PORT=5000
MONGO_URI=mongodb://localhost:27017/blog-api
JWT_SECRET=yourSecretKey

🧩 四、数据库模型设计(Mongoose)

用户模型 user.js

javascript 复制代码
js
复制编辑
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

userSchema.pre('save', async function(next) {
  this.password = await bcrypt.hash(this.password, 10);
  next();
});

module.exports = mongoose.model('User', userSchema);

🔐 五、JWT 鉴权中间件

middlewares/auth.js

ini 复制代码
js
复制编辑
const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  const token = req.header('Authorization')?.split(' ')[1];
  if (!token) return res.status(401).json({ msg: 'No token, auth denied' });

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch {
    res.status(401).json({ msg: 'Token is not valid' });
  }
};

📨 六、用户注册与登录接口

controllers/auth.js(简略):

ini 复制代码
js
复制编辑
exports.register = async (req, res) => {
  const { username, password } = req.body;
  const user = new User({ username, password });
  await user.save();
  res.json({ msg: 'User created' });
};

exports.login = async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) return res.status(400).json({ msg: 'Invalid credentials' });

  const token = jwt.sign({ user: { id: user.id } }, process.env.JWT_SECRET);
  res.json({ token });
};

📃 七、文章增删改查 API 示例

Post 模型

php 复制代码
js
复制编辑
const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  title: String,
  content: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
}, { timestamps: true });

module.exports = mongoose.model('Post', postSchema);

控制器 posts.js(简要)

ini 复制代码
js
复制编辑
exports.createPost = async (req, res) => {
  const post = new Post({ ...req.body, author: req.user.id });
  await post.save();
  res.json(post);
};

exports.getPosts = async (req, res) => {
  const posts = await Post.find().populate('author', 'username');
  res.json(posts);
};

📡 八、接口测试与运行方式

启动服务:

复制代码
bash
复制编辑
npx nodemon app.js

Postman 测试顺序建议:

  1. 注册 → /api/auth/register
  2. 登录获取 token → /api/auth/login
  3. 携带 token 调用文章接口 → /api/posts

📦 九、可扩展方向

  • 接入 Swagger API 文档
  • 引入 Redis 做缓存
  • Docker 化部署
  • 统一错误处理(Error Handler 中间件)

✅ 十、项目总结

  • Node + MongoDB 非常适合中小型 RESTful 服务开发
  • 通过 Express + Mongoose 能快速建模与部署
  • JWT 鉴权简单有效,适合移动端、SPA 场景
相关推荐
桦说编程21 小时前
Guava 迭代器增强类介绍
java·后端·设计模式
2351621 小时前
【JVM】Java为啥能跨平台?JDK/JRE/JVM的关系?
java·开发语言·jvm·spring boot·后端·spring·职场和发展
courtfu21 小时前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端
上进小菜猪1 天前
测试自动化Replay:让数据库迁移测试回归真实场景的一把“利器”
后端
Python私教1 天前
FastAPI × SQLAlchemy 2.0 Async:从“能跑”到“可压测”的完整工程实践
后端
Python私教1 天前
FastAPI × Loguru:从“能跑”到“可运维”的日志实战
后端
Craaaayon1 天前
如何选择两种缓存更新策略(写缓存+异步写库;写数据库+异步更新缓存)
java·数据库·redis·后端·缓存·mybatis
唐僧洗头爱飘柔95271 天前
【GORM(3)】Go的跨时代ORM框架!—— 数据库连接、配置参数;本文从0开始教会如何配置GORM的数据库
开发语言·数据库·后端·golang·gorm·orm框架·dsn
Jonathan Star1 天前
在 Go 语言中,模板字符串
开发语言·后端·golang
盘古开天16661 天前
从零开始:如何搭建你的第一个简单的Flask网站
后端·python·flask