跳到主要内容

[技术/功能] 完整教程

难度级别:★★★☆☆ (初级/中级/高级)
预计时间:30分钟
更新日期:2025-01-20
作者:[作者姓名]


教程目标

完成本教程后,你将学会:

  • 目标 1:掌握核心概念
  • 目标 2:完成实际项目
  • 目标 3:理解最佳实践
  • 目标 4:能够独立开发

准备工作

前置知识

在开始本教程前,你需要了解:

  • JavaScript基础知识
  • Node.js基本使用
  • 命令行操作

环境准备

软件版本下载链接
Node.js18+nodejs.org
VS Code最新版code.visualstudio.com
Git2.0+git-scm.com

第一步:项目初始化

1.1 创建项目目录

bash
1# 创建项目文件夹
2mkdir my-awesome-project
3cd my-awesome-project
4
5# 初始化Git仓库
6git init
7
8# 初始化npm项目
9npm init -y
💡 小贴士

使用 npm init -y 可以快速创建 package.json,跳过交互式提问。

1.2 安装依赖

bash
1npm install express mongoose dotenv
2npm install --save-dev nodemon

1.3 项目结构

创建以下目录结构:

1my-awesome-project/
2├── src/
3│ ├── controllers/
4│ ├── models/
5│ ├── routes/
6│ └── index.js
7├── .env
8├── .gitignore
9└── package.json
bash
1# 创建目录
2mkdir -p src/{controllers,models,routes}
3
4# 创建文件
5touch src/index.js .env .gitignore

第二步:编写核心代码

2.1 创建服务器

src/index.js 中编写代码:

src/index.js
javascript
1const express = require('express');
2const app = express();
3// highlight-next-line
4const PORT = process.env.PORT || 3000;
5
6// 中间件配置
7app.use(express.json());
8// highlight-start
9app.use(express.urlencoded({ extended: true }));
10// highlight-end
11
12// 健康检查接口
13app.get('/health', (req, res) => {
14 res.json({ status: 'OK', timestamp: new Date().toISOString() });
15});
16
17// 启动服务器
18app.listen(PORT, () => {
19 console.log(`Server is running on http://localhost:${PORT}`);
20});
代码说明
  • 第3-5行:定义服务器端口
  • 第8-10行:配置中间件,支持JSON和URL编码

2.2 创建数据模型

src/models/User.js
javascript
1const mongoose = require('mongoose');
2
3const userSchema = new mongoose.Schema({
4 username: {
5 type: String,
6 required: true,
7 unique: true,
8 trim: true,
9 minlength: 3,
10 maxlength: 20
11 },
12 email: {
13 type: String,
14 required: true,
15 unique: true,
16 lowercase: true,
17 match: /^\S+@\S+\.\S+$/
18 },
19 password: {
20 type: String,
21 required: true,
22 minlength: 6
23 },
24 createdAt: {
25 type: Date,
26 default: Date.now
27 }
28});
29
30module.exports = mongoose.model('User', userSchema);

第三步:实现业务逻辑

3.1 用户注册功能

src/controllers/userController.js
javascript
1const User = require('../models/User');
2const bcrypt = require('bcryptjs');
3
4exports.register = async (req, res) => {
5 try {
6 const { username, email, password } = req.body;
7
8 // 1. 验证输入
9 if (!username || !email || !password) {
10 return res.status(400).json({
11 success: false,
12 message: '请填写完整信息'
13 });
14 }
15
16 // 2. 检查用户是否已存在
17 const existingUser = await User.findOne({
18 $or: [{ email }, { username }]
19 });
20
21 if (existingUser) {
22 return res.status(409).json({
23 success: false,
24 message: '用户名或邮箱已被注册'
25 });
26 }
27
28 // 3. 加密密码
29 const hashedPassword = await bcrypt.hash(password, 10);
30
31 // 4. 创建用户
32 const newUser = new User({
33 username,
34 email,
35 password: hashedPassword
36 });
37
38 await newUser.save();
39
40 // 5. 返回成功响应(不返回密码)
41 res.status(201).json({
42 success: true,
43 message: '注册成功',
44 data: {
45 id: newUser._id,
46 username: newUser.username,
47 email: newUser.email
48 }
49 });
50
51 } catch (error) {
52 console.error('注册错误:', error);
53 res.status(500).json({
54 success: false,
55 message: '服务器错误'
56 });
57 }
58};

第四步:测试功能

4.1 启动服务器

bash
1# 开发模式(自动重启)
2npm run dev
3
4# 或使用 nodemon
5nodemon src/index.js

4.2 测试API

使用cURL测试注册接口:

bash
1curl -X POST http://localhost:3000/api/register \
2 -H "Content-Type: application/json" \
3 -d '{
4 "username": "testuser",
5 "email": "test@example.com",
6 "password": "password123"
7 }'

预期响应:

json
1{
2 "success": true,
3 "message": "注册成功",
4 "data": {
5 "id": "507f1f77bcf86cd799439011",
6 "username": "testuser",
7 "email": "test@example.com"
8 }
9}

第五步:优化与部署

5.1 添加环境变量

编辑 .env 文件:

.env
env
1PORT=3000
2MONGODB_URI=mongodb://localhost:27017/myapp
3JWT_SECRET=your-super-secret-key
4NODE_ENV=development
⚠️ 安全提示

永远不要将 .env 文件提交到版本控制!请将它添加到 .gitignore

5.2 添加错误处理

src/middleware/errorHandler.js
javascript
1module.exports = (err, req, res, next) => {
2 console.error(err.stack);
3
4 res.status(err.status || 500).json({
5 success: false,
6 message: err.message || '服务器错误',
7 ...(process.env.NODE_ENV === 'development' && {
8 stack: err.stack
9 })
10 });
11};

5.3 Docker化部署

Dockerfile
dockerfile
1FROM node:18-alpine
2
3WORKDIR /app
4
5COPY package*.json ./
6RUN npm ci --only=production
7
8COPY . .
9
10EXPOSE 3000
11
12CMD ["node", "src/index.js"]

总结

恭喜你完成了本教程!你已经学会了:

  • 如何搭建Node.js项目
  • 如何使用Express创建API
  • 如何使用MongoDB存储数据
  • 如何实现用户注册功能
  • 如何测试和部署应用

扩展阅读

进阶主题

  1. 安全性增强

    • 实现JWT认证
    • 添加请求限流
    • 防止SQL注入
  2. 性能优化

    • 添加Redis缓存
    • 数据库索引优化
    • 使用PM2进行进程管理
  3. 测试

    • 单元测试(Jest)
    • 集成测试(Supertest)
    • 端到端测试

相关资源


💬 练习题

练习1:添加用户登录功能

实现用户登录接口,要求:

  • 验证用户名和密码
  • 返回JWT token
  • 处理错误情况

练习2:实现密码重置

创建密码重置流程:

  • 发送重置邮件
  • 验证重置令牌
  • 更新用户密码

常见问题

Q1: 连接MongoDB失败

问题MongoNetworkError: connection refused

解决方案

bash
1# 检查MongoDB是否运行
2mongod --version
3
4# 启动MongoDB
5# Windows
6net start MongoDB
7
8# Linux/Mac
9sudo systemctl start mongod

Q2: 端口被占用

问题Error: listen EADDRINUSE: address already in use :::3000

解决方案

bash
1# 查找占用端口的进程
2# Windows
3netstat -ano | findstr :3000
4
5# Linux/Mac
6lsof -i :3000
7
8# 终止进程或更换端口

🤝 反馈与贡献

如果你发现教程中的问题,或有改进建议,欢迎:


🎉 恭喜!

你已经完成了整个教程!现在试着自己构建一个完整的应用吧!

评论