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

Express 是一个简洁而灵活的 Node.js Web 应用框架,提供了一套强大功能帮助你快速构建 Web 应用和 API。它本身轻量,但通过中间件机制可高度扩展。如果你刚接触 Node.js 后端开发,Express 是非常理想的起点。下面带你从零开始快速上手,并完成一个简单的项目实战。
确保你的系统已安装 Node.js(建议 v14 或以上版本)。打开终端执行以下命令:
mkdir my-express-app && cd my-express-app
npm init -y
npm install express
创建入口文件 app.js,写入最基础的服务器代码:
const express = require('express');
const app = express();
const PORT = 3000;
<p>app.get('/', (req, res) => {
res.send('Hello from Express!');
});</p><p>app.listen(PORT, () => {
console.log(<code>Server is running at http://localhost:${PORT}</code>);
});
运行 node app.js,浏览器访问 http://localhost:3000 即可看到输出内容。
Express 使用 app.METHOD(path, callback) 定义路由。常见的 METHOD 包括 get、post、put、delete 等。
: 定义示例:添加多个路由
app.get('/users', (req, res) => {
res.json({ users: ['Alice', 'Bob'] });
});
<p>app.get('/users/:id', (req, res) => {
const id = req.params.id;
res.json({ userId: id });
});</p><p>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() 继续流程
});
该中间件会打印每次请求的时间、方法和路径。
我们来实现一个支持增删改查(CRUD)的笔记接口。
创建 notes.js 模拟数据存储:
let notes = [
{ id: 1, title: '学习 Express', content: '今天学会了路由和中间件' }
];
<p>module.exports = notes;
在 app.js 中引入并定义 CRUD 路由:
const notes = require('./notes');
<p>// 获取所有笔记
app.get('/api/notes', (req, res) => {
res.json(notes);
});</p><p>// 获取单个笔记
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);
});</p><p>// 创建笔记
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);
});</p><p>// 更新笔记
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');</p><p>note.title = req.body.title || note.title;
note.content = req.body.content || note.content;
res.json(note);
});</p><p>// 删除笔记
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');</p><p>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');
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 解析。多练习,自然熟练。
以上就是Express框架怎么使用_Express框架快速上手与项目实战详细教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号