免费获取学习方案
BACK-END TUTORIAL

后端开发教程

从 Node.js 基础到 Express 框架实战,RESTful API 设计、身份认证与数据库连接,构建可扩展的服务端应用。

后端开发教程:Node.js 与服务端实战

后端开发教程

后端开发负责处理业务逻辑、数据存储与接口提供,是 Web 应用中"看不见但至关重要"的部分。本教程以 Node.js + Express 技术栈为主线,系统讲解服务端开发的核心知识。

1. Node.js 基础

Node.js 是基于 V8 引擎的 JavaScript 运行时,让 JS 跑在服务端。它采用事件驱动、非阻塞 I/O 模型,适合构建高并发网络应用。

// hello-server.js —— 一个最简 HTTP 服务
const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ code: 0, msg: "Hello from Node.js" }));
});

server.listen(3000, () => {
  console.log("服务已启动:http://localhost:3000");
});

node hello-server.js 启动后,访问 http://localhost:3000 即可看到返回的 JSON 数据。建议使用 nodemon 自动重启开发。

2. 模块化机制

Node.js 支持 CommonJS 与 ES Module 两种模块规范。CommonJS 使用 require/module.exports,ES Module 使用 import/export

// utils.js —— CommonJS 导出
function formatDate(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}
module.exports = { formatDate };

// app.js —— 引入使用
const { formatDate } = require("./utils");
console.log(formatDate(new Date()));

3. Express 框架

Express 是 Node.js 最流行的 Web 框架,提供路由、中间件、模板引擎等能力,极大简化了 HTTP 服务开发。

const express = require("express");
const app = express();

// 解析 JSON 请求体
app.use(express.json());

// 定义路由
app.get("/", (req, res) => {
  res.json({ msg: "API 服务运行中" });
});

app.get("/users/:id", (req, res) => {
  const { id } = req.params;
  res.json({ id, name: "用户" + id });
});

app.listen(3000, () => console.log("API 启动于 3000"));

4. RESTful API 设计

REST 是一种基于 HTTP 动词语义的接口设计风格,用 URL 表示资源,用方法表示操作。

// 用户资源 CRUD
app.get("/api/users", listUsers);        // 列表
app.get("/api/users/:id", getUser);      // 详情
app.post("/api/users", createUser);      // 创建
app.put("/api/users/:id", updateUser);  // 全量更新
app.patch("/api/users/:id", patchUser);  // 部分更新
app.delete("/api/users/:id", deleteUser);// 删除

// 统一响应格式
function ok(res, data, msg = "success") {
  res.json({ code: 0, msg, data });
}
function fail(res, msg = "error", code = 1) {
  res.json({ code, msg, data: null });
}
命名建议:URL 使用复数名词 /users、用连字符 user-profiles、避免动词。版本号放路径 /api/v1/users,便于平滑升级。

5. JWT 身份认证

JSON Web Token 是无状态的认证方案,服务端签发令牌,客户端携带令牌请求,服务端验证签名即可识别用户身份。

const jwt = require("jsonwebtoken");
const SECRET = "your-secret-key";

// 登录成功后签发令牌
function login(req, res) {
  const { username, password } = req.body;
  const user = verifyUser(username, password);
  if (!user) return res.status(401).json({ msg: "账号或密码错误" });

  const token = jwt.sign(
    { uid: user.id, role: user.role },
    SECRET,
    { expiresIn: "7d" }
  );
  res.json({ token, user });
}

// 中间件:校验令牌
function auth(req, res, next) {
  const token = req.headers.authorization?.replace("Bearer ", "");
  if (!token) return res.status(401).json({ msg: "未登录" });
  try {
    req.user = jwt.verify(token, SECRET);
    next();
  } catch (e) {
    res.status(401).json({ msg: "令牌无效" });
  }
}

6. 数据库连接

以 MySQL 为例,推荐使用连接池(Pool)管理连接,避免频繁建立/断开带来的性能损耗。

const mysql = require("mysql2/promise");

const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "your_password",
  database: "pgsr",
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

async function findUserById(id) {
  // 使用 ? 占位符,自动转义防注入
  const [rows] = await pool.execute(
    "SELECT id, name, email FROM users WHERE id = ?",
    [id]
  );
  return rows[0];
}

永远不要用字符串拼接构造 SQL,必须使用参数化查询,否则会留下 SQL 注入漏洞。

7. 中间件机制

Express 的中间件是按顺序执行的函数,可统一处理日志、跨域、鉴权、错误捕获等横切关注点。

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

// 跨域中间件
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
  next();
});

// 全局错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ code: 500, msg: "服务器内部错误" });
});

8. 项目部署

生产环境推荐使用 PM2 进程管理工具,实现守护进程、自动重启、负载均衡与日志收集。

# 全局安装 PM2
npm install -g pm2

# 启动应用并命名
pm2 start app.js --name pgsr-api

# 常用命令
pm2 list            # 查看所有进程
pm2 logs pgsr-api   # 查看日志
pm2 restart pgsr-api
pm2 stop pgsr-api
pm2 startup         # 开机自启
pm2 save            # 保存当前进程列表

结语与进阶

掌握上述内容即可独立开发并部署一个中小型后端服务。后续可继续深入:

  1. ORM 框架:Sequelize、Prisma,提升数据库操作效率
  2. WebSocket:实时通信,构建聊天室、协作工具
  3. 微服务与容器化:Docker + Nginx 反向代理
  4. 性能监控:APM 工具、日志聚合、链路追踪
实战建议:完成本教程后,尝试用 Express + MySQL 实现一个带注册登录、文章 CRUD 与评论功能的博客 API,把所有知识点串起来。
下一篇:数据库运维 →