@koa/route demo
在 Node.js 生态中,你提到的
@koa/route 通常指向两个社区中最主流的 Koa 路由中间件:这里为你提供在 2026 年技术栈下,基于官方首推、完全原生支持 TypeScript/ESM 的
@koa/router 编写的完整路由系统 Demo,涵盖了 路径参数、Query 参数、POST Body 解析、以及路由模块化分拆 等核心高频场景。 [1]📦 1. 环境准备与依赖安装
Koa 本身不包含任何路由和请求体解析逻辑,需要安装对应的标准中间件:
bash
npm install koa @koa/router koa-bodyparser
请谨慎使用此类代码。
📂 2. 子路由模块划分(
routes/user.js)javascript
// routes/user.js
const Router = require('@koa/router');
// 💡 1. 实例化路由并配置前缀
const userRouter = new Router({
prefix: '/users'
});
// 🚀 场景 A: GET 请求 + 动态路径参数 (Named URL parameters)
// 示例 URL: GET http://127.0.0
userRouter.get('/:id', async (ctx, next) => {
// 从 ctx.params 中直接提取路径参数
const userId = ctx.params.id;
ctx.body = {
status: 'success',
data: { id: userId, name: `用户_${userId}`, age: 18 }
};
});
// 🚀 场景 B: GET 请求 + URL 查询参数 (Query Parameters)
// 示例 URL: GET http://127.0.0
userRouter.get('/', async (ctx, next) => {
// 从 ctx.query 中直接获取问号后面的参数对象
const { page = 1, size = 10 } = ctx.query;
ctx.body = {
page: Number(page),
size: Number(size),
list: [{ id: 1, name: '马良' }]
};
});
// 🚀 场景 C: POST 请求 + Body 请求体解析 (需要引入 koa-bodyparser 中间件)
// 示例 URL: POST http://127.0.0
userRouter.post('/', async (ctx, next) => {
// 经 bodyparser 插件处理后,前端传来的 JSON 可以从 ctx.request.body 中直接拿到
const { username, age } = ctx.request.body;
if (!username) {
ctx.status = 400;
ctx.body = { error: '用户名不能为空' };
return;
}
ctx.status = 201;
ctx.body = {
message: '创建成功',
user: { id: 99, username, age }
};
});
// 导出路由供主入口文件挂载
module.exports = userRouter;
请谨慎使用此类代码。
🔌 3. 主应用入口文件挂载(
app.js)javascript
// app.js
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
// 💡 引入子路由模块
const userRouter = require('./routes/user');
const app = new Koa();
const PORT = 3000;
// 1. 挂载基础中间件:必须在路由注册之前挂载 bodyParser,否则路由内部拿不到 POST 数据!
app.use(bodyParser());
// 2. 挂载子路由
app.use(userRouter.routes());
// 3. 挂载允许的请求方法中间件
// 作用:当请求方法不匹配时(例如前端用 POST 请求了一个只定义了 GET 的接口),自动返回 405 Method Not Allowed
app.use(userRouter.allowedMethods());
// 4. 根路径拦截做个简单响应测试
app.use(async (ctx, next) => {
if (ctx.path === '/') {
ctx.body = { message: '欢迎来到 Koa 路由首页' };
} else {
await next();
}
});
// 启动服务
app.listen(PORT, () => {
console.log(`🚀 Koa 服务器已成功启动: http://127.0.0.1:${PORT}`);
});
请谨慎使用此类代码。
💡 核心注意与避坑指南
.allowedMethods()的必要性:很多初学者容易漏掉app.use(router.allowedMethods())。它不仅能帮你自动处理OPTIONS跨域预检请求,还能在客户端使用错误 HTTP 动词时提供规范的405 (方法不允许)或501 (未实现)状态码返回。- 中间件顺序(洋葱模型):在 Koa 中,数据流和权限拦截均依托于中间件洋葱模型。如果你想要在进入路由前执行用户登录鉴权(Token 校验),应该在
app.use(router.routes())的上方挂载一个鉴权拦截函数。 [1, 2, 3]
你目前是要在路由中加入 JWT Token 用户鉴权中间件,还是需要做多层多级的路由嵌套(例如 /api/v1/users)?告诉我你的工程设计,我为你扩写进阶代码。
漫思
浙公网安备 33010602011771号