Node系列 · Express:基本使用

Node系列 · Express:基本使用 Node系列 · Express基本使用Express 是 Node 生态最老牌、最流行的 Web 框架——Koa 是同一作者TJ后续更轻量的作品Fastify / NestJS 是更新的高性能替代。本章从零起步搭建一个 Express 服务理解它的核心约定。一、Express 与同类框架对比框架风格性能生态何时选Express中间件链式回调一般最大老项目 / 通用Koa2async/await 中间件略好中等现代项目Fastify插件式最快增长中性能敏感NestJS装饰器 DI一般大企业级 / 团队Express 不一定是最好的但学习曲线最低、文档最全、第三方中间件最多——新项目入门首选。二、安装与最小服务mkdirmy-appcdmy-appnpminit-ynpminstallexpressconst express require(express); const app express(); app.get(/, (req, res) { res.send(Hello World); }); app.listen(3000, () { console.log(服务运行在 http://localhost:3000); });$nodeapp.js 服务运行在 http://localhost:3000三、官方资源资源地址英文官网expressjs.com中文官网expressjs.com.cnGitHubexpressjs/express四、REST 风格路由Express 推荐按 RESTful 风格设计路由——HTTP 方法 URL 表达对资源的操作方法路径含义GET/users用户列表GET/users/:id单个用户详情POST/users创建用户PUT/users/:id整体更新用户PATCH/users/:id部分更新用户DELETE/users/:id删除用户app.get(/users, listUsers); app.get(/users/:id, getUser); app.post(/users, createUser); app.put(/users/:id, updateUser); app.patch(/users/:id, partialUpdateUser); app.delete(/users/:id, deleteUser);五、与原生 http 模块的关系Express 是http模块的封装底层完全一样Express app.get ...Express 框架http.createServernet.SocketTCP/IP每一段app.get(path, handler)内部注册到 Express 的路由表http 服务收到请求后匹配 path匹配到时调用 handlerhandler 里通过res.send()/res.json()返回响应Express 的价值不是性能而是抽象掉 HTTP 协议解析——让你专注业务逻辑。六、第一个完整服务const express require(express); const app express(); // JSON body 解析Content-Type: application/json app.use(express.json()); // 模拟数据库 const users [ { id: 1, name: Alice }, { id: 2, name: Bob }, ]; // 路由 app.get(/api/users, (req, res) { res.json({ users }); }); app.get(/api/users/:id, (req, res) { const user users.find((u) u.id Number(req.params.id)); if (!user) { return res.status(404).json({ error: User not found }); } res.json(user); }); app.post(/api/users, (req, res) { const newUser { id: users.length 1, ...req.body }; users.push(newUser); res.status(201).json(newUser); }); app.listen(3000, () { console.log(http://localhost:3000); });测试$curlhttp://localhost:3000/api/users{users:[{id:1,name:Alice},{id:2,name:Bob}]}$curl-XPOST-HContent-Type: application/json\-d{name:Carol}http://localhost:3000/api/users{id:3,name:Carol}七、最佳实践场景推荐项目起步npm initnpm install express路由设计REST 风格GET / POST / PUT / DELETEJSON 接口app.use(express.json())解析请求体文件上传multer中间件跨域cors中间件详见 跨域 CORS路由拆分express.Router()详见 路由自动重启nodemon见 nodemon 章节八、小结Express 是 Node 老牌 Web 框架最小服务 5 行代码推荐 REST 风格HTTP 方法 URL 表达资源操作Express 是http模块的封装底层完全一致项目结构app.js入口 路由模块 中间件中文文档expressjs.com.cn