Express框架怎么使用_Express框架快速上手与项目实战详细教程

Express 是快速构建 Web 应用和 API 的 Node.js 框架,通过路由、中间件实现请求处理,结合项目实战掌握 CRUD 接口开发并推荐代码分层结构以提升可维护性。

Express 是一个简洁而灵活的 Node.js Web 应用框架,提供了一套强大功能帮助你快速构建 Web 应用和 API。它本身轻量,但通过中间件机制可高度扩展。如果你刚接触 Node.js 后端开发,Express 是非常理想的起点。下面带你从零开始快速上手,并完成一个简单的项目实战。

一、安装与初始化 Express 项目

确保你的系统已安装 Node.js(建议 v14 或以上版本)。打开终端执行以下命令:

  • 创建项目目录:mkdir my-express-app && cd my-express-app
  • 初始化项目:npm init -y
  • 安装 Express:npm install express

创建入口文件 app.js,写入最基础的服务器代码:

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => { res.send('Hello from Express!'); });

app.listen(PORT, () => { console.log(Server is running at http://localhost:${PORT}); });

运行 node app.js,浏览器访问 http://localhost:3000 即可看到输出内容。

二、路由与请求处理

Express 使用 app.METHOD(path, callback) 定义路由。常见的 METHOD 包括 get、post、put、delete 等。

  • GET 请求:获取数据
  • POST 请求:提交数据
  • 动态路由参数使用冒号 : 定义

示例:添加多个路由

app.get('/users', (req, res) => {
  res.json({ users: ['Alice', 'Bob'] });
});

app.get('/users/:id', (req, res) => { const id = req.params.id; res.json({ userId: id }); });

app.post('/users', (req, res) => { res.status(201).send('User created'); });

注意:POST 请求需要解析请求体,需使用中间件。

三、使用中间件处理请求数据

中间件是 Express 的核心概念,用于在请求-响应周期中执行代码,如日志记录、身份验证、数据解析等。

常用内置中间件:

app.use(express.json()); // 解析 JSON 请求体
app.use(express.urlencoded({ extended: true })); // 解析表单数据

自定义中间件示例:

app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next(); // 必须调用 next() 继续流程
});

该中间件会打印每次请求的时间、方法和路径。

四、项目实战:构建一个简易笔记 API

我们来实现一个支持增删改查(CRUD)的笔记接口。

创建 notes.js 模拟数据存储:

let notes = [
  { id: 1, title: '学习 Express', content: '今天学会了路由和中间件' }
];

module.exports = notes;

app.js 中引入并定义 CRUD 路由:

const notes = require('./notes');

// 获取所有笔记 app.get('/api/notes', (req, res) => { res.json(notes); });

// 获取单个笔记 app.get('/api/notes/:id', (req, res) => { const note = notes.find(n => n.id == req.params.id); if (!note) return res.status(404).send('Note not found'); res.json(note); });

// 创建笔记 app.post('/api/notes', (req, res) => { const { title, content } = req.body; const newNote = { id: notes.length + 1, title, content }; notes.push(newNote); res.status(201).json(newNote); });

// 更新笔记 app.put('/api/notes/:id', (req, res) => { const id = req.params.id; const note = notes.find(n => n.id == id); if (!note) return res.status(404).send('Note not found');

note.title = req.body.title || note.title; note.content = req.body.content || note.content; res.json(note); });

// 删除笔记 app.delete('/api/notes/:id', (req, res) => { const id = req.params.id; const index = notes.findIndex(n => n.id == id); if (index === -1) return res.status(404).send('Note not found');

notes.splice(index, 1); res.status(204).send(); // 无内容返回 });

使用 Postman 或 curl 测试这些接口,确认功能正常。

五、静态文件服务与模板引擎(可选扩展)

若要服务 HTML、CSS、JS 文件,使用 express.static

app.use(express.static('public'));

在 public 目录下放 index.html,即可直接访问。

集成模板引擎如 EJS:

  • 安装:npm install ejs
  • 设置视图引擎:app.set('view engine', 'ejs');
  • 创建 views/list.ejs,使用 res.render('list', { data }) 渲染页面

六、项目结构优化建议

随着项目变大,应拆分代码。推荐结构:

my-express-app/
├── app.js
├── routes/
│   └── notesRoute.js
├── controllers/
│   └── notesController.js
├── models/
│   └── Note.js
└── public/
    └── css/, js/

将路由逻辑移到 routes/notesRoute.js,控制器方法放入 controllers/notesController.js,保持代码清晰可维护。

基本上就这些。掌握 Express 的核心在于理解路由、中间件和请求响应流程。动手实现一个小项目能最快巩固知识。不复杂但容易忽略细节,比如忘记调用 next() 或未启用 body 解析。多练习,自然熟练。