@eggjs/router

中文文档
4.1.0发布于 2026/10/07MITTypeScriptES Module构建来源已验证近 30 天下载 9.6万

蛋/可口的路由器中间软件. 提供 REST 资源路径 .

中文使用文档
文档目录7 节
  1. API 参考
  2. 路由器QQ
  3. 嵌入路由器
  4. 测试
  5. V3 正在中断更改
  6. 许可证
  7. 贡献者

@eggjs/路由器

NPM version NPM download Known Vulnerabilities Node.js Version PRs Welcome CodeRabbit Pull Request Reviews

路由器核心组件用于 鸡蛋.js。 。 。 .

此寄存器为 旋转道。 。 。 . 带有一些额外特征. 感谢@alexmingoia和原始团队的出色工作.

API 参考

路由器QQ

仁爱: 导出类别

新建路由器( [opts] )

创建新路由器 .

参数类型说明
[选择]Object
[opts.prefix] (英语)String前缀路由器路径

示例 基本用途:

import Koa from '@eggjs/koa';
import Router from '@eggjs/router';

const app = new Koa();
const router = new Router();

router.get('/', async (ctx, next) => {
  // ctx.router available
});

app.use(router.routes()).use(router.allowedMethods());

路由器 Router

创建 router.verb() 方法,其中 动词 是HTTP 动词之一 作为 router.get() 或者说 router.post()。 。 。 .

匹配 URL 模式以调用调用函数或控制器动作 router.verb(), (中文(简体) ), 地点 动词 hTTP 等动词之一 router.get() 或者说 router.post()。 。 。 .

还有, router.all() 可以用来匹配所有方法.

router
  .get('/', (ctx, next) => {
    ctx.body = 'Hello World!';
  })
  .post('/users', (ctx, next) => {
    // ...
  })
  .put('/users/:id', (ctx, next) => {
    // ...
  })
  .del('/users/:id', (ctx, next) => {
    // ...
  })
  .all('/users/:id', (ctx, next) => {
    // ...
  });

当一个路径匹配时, 它的路径可用于 ctx.routePath 并且如果命名, 名称在 ctx.routeName

路由路径将使用 路径到备忘。 。 。 .

匹配请求时不考虑查询字符串 .

命名路线

路由可以选择有名称. 这样可以生成 URL 和 简单 开发期间重新命名 URL.

router.get('user', '/users/:id', (ctx, next) => {
  // ...
});

router.url('user', 3);
// => "/users/3"

多个中间软件

多个中间软件可能给出:

router.get(
  '/users/:id',
  (ctx, next) => {
    return User.findOne(ctx.params.id).then(function (user) {
      ctx.user = user;
      next();
    });
  },
  (ctx) => {
    console.log(ctx.user);
    // => { id: 17, name: "Alex" }
  },
);

嵌入路由器

支持嵌入路由器 :

const forums = new Router();
const posts = new Router();

posts.get('/', (ctx, next) => {...});
posts.get('/:pid', (ctx, next) => {...});
forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());

// responds to "/forums/123/posts" and "/forums/123/posts/123"
app.use(forums.routes());

路由器前缀

路径可以在路由器级别前缀:

const router = new Router({
  prefix: '/users'
});

router.get('/', ...); // responds to "/users"
router.get('/:id', ...); // responds to "/users/:id"

URL 参数

获取并添加命名的路由参数 ctx.params。 。 。 .

router.get('/:category/:title', (ctx, next) => {
  console.log(ctx.params);
  // => { category: 'programming', title: 'how-to-node' }
});

这个 路径到备忘 模块是 用于将路径转换为正则表达式.

仁爱: 实例财产 Router

参数类型说明
路径String
[中function路由中间软件
回调function路由调用

路由器. 路由器 qq function

返回发送匹配请求的路由器中间软件 .

仁爱: 实例财产 Router

路由器.use([path],中间软件) qq Router

使用给定的中间软件 .

中间软件按定义顺序运行 .use()它们被援引 依次从第一个中间器件开始请求并按自己的方式工作 "下"中相器叠.

仁爱: 实例方法 Router

参数类型
[路径]String
中间软件function
[...]function

示例

// session middleware will run before authorize
router.use(session()).use(authorize());

// use middleware only with given path
router.use('/users', userAuth());

// or with an array of paths
router.use(['/users', '/admin'], userAuth());

app.use(router.routes());

路由器. prefix( 前缀) qq Router

为已经初始化的路由器实例设置路径前缀 .

仁爱: 实例方法 Router

参数类型
前缀String

示例

router.prefix('/things/:thing_id');

路由器. allowd Methods ([可选 ) QQ function

返回响应的单独中间软件 OPTIONS 请求 a 一个 Allow 包含允许的方法以及响应的页眉 与 405 Method Not Allowed 财务报告和审定财务报表 501 Not Implemented 视情况而定.

仁爱: 实例方法 Router

参数类型说明
[可选Object
[选项.推Boolean丢弃错误而不是设置状态和页眉
[选项. not 已执行]function将返回的值扔出以取代默认未执行错误
[选项.方法不全]function丢弃返回的值以取代默认方法Not Allowed 错误

示例

import Koa from '@eggjs/koa';
import Router from '@eggjs/router';

const app = new Koa();
const router = new Router();

app.use(router.routes());
app.use(router.allowedMethods());

示例 轰

import Koa from '@eggjs/koa';
import Router from '@eggjs/router';
import Boom from 'boom';

const app = new Koa();
const router = new Router();

app.use(router.routes());
app.use(
  router.allowedMethods({
    throw: true,
    notImplemented: () => new Boom.notImplemented(),
    methodNotAllowed: () => new Boom.methodNotAllowed(),
  }),
);

路由器. redirect(来源,目的地,[代码]) qq Router

重定向 source 改为 destination 可选 30x 状态的 URL code。 。 。 .

两者 source 财务报告和审定财务报表 destination 可以是路由名称.

router.redirect('/login', 'sign-in');

这相当于:

router.all('/login', (ctx) => {
  ctx.redirect('/sign-in');
  ctx.status = 301;
});

仁爱: 实例方法 Router

参数类型说明
来源StringURL或路由名称.
目标StringURL或路由名称.
[编码]NumberHTTP 状态代码( 默认: 301).

路由器.route(名称) qq Layer | false

以给定的查找路径 name。 。 。 .

仁爱: 实例方法 Router

参数类型
名称String

路由器.url(名称,参数,[可选 ) qq String | Error

生成路由的 URL 。 使用命名的路由名称和地图 params。 。 。 .

仁爱: 实例方法 Router

参数类型说明
名称String路由名称
段落Objecturl 参数
[可选Object选项参数
[选项.query]Object | String查询选项

示例

router.get('user', '/users/:id', (ctx, next) => {
  // ...
});

router.url('user', 3);
// => "/users/3"

router.url('user', { id: 3 });
// => "/users/3"

router.use((ctx, next) => {
  // redirect to named route
  ctx.redirect(ctx.router.url('sign-in'));
});

router.url('user', { id: 3 }, { query: { limit: 1 } });
// => "/users/3?limit=1"

router.url('user', { id: 3 }, { query: 'limit=1' });
// => "/users/3?limit=1"

路由器.param( parm, 中间软件) qq Router

运行命名路由参数的中间软件 。 用于自动装入或 审定.

仁爱: 实例方法 Router

参数类型
段落String
中间软件function

示例

router
  .param('user', (id, ctx, next) => {
    ctx.user = users[id];
    if (!ctx.user) return (ctx.status = 404);
    return next();
  })
  .get('/users/:user', (ctx) => {
    ctx.body = ctx.user;
  })
  .get('/users/:user/friends', (ctx) => {
    return ctx.user.getFriends().then(function (friends) {
      ctx.body = friends;
    });
  });
// /users/3 => {"id": 3, "name": "Alex"}
// /users/3/friends => [{"id": 4, "name": "TJ"}]

Router.url(路径,参数[,选项]) QQ String

从 url 模式生成 URL并给出 params。 。 。 .

仁爱:静态方法 Router

参数类型说明
路径Stringurl 模式
段落Objecturl 参数
[可选Object选项参数
[选项.query]Object | String查询选项

示例

const url = Router.url('/users/:id', { id: 1 });
// => "/users/1"

const url = Router.url('/users/:id', { id: 1 }, { query: { active: true } });
// => "/users/1?active=true"

测试

使用 npm test。 。 。 .

V3 正在中断更改

  • 丢弃生成器函数支持
  • 丢出节点.js < 18.19.0 支持

许可证

麻省理工学院

贡献者

Contributors

制造的 贡献者-img。 。 。 .

版本与发布记录

@eggjs/router 共发布 68 个版本,首次发布于 2019/01/30;过去 12 个月发布了 33 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.1.0latest2026/10/071 个月前
4.0.22026/10/061 个月前
4.0.2-rc.1rc2026/10/061 个月前
4.0.2-rc.02026/09/231 个月前
4.0.2-beta.27beta2026/09/201 个月前
4.0.2-beta.262026/08/073 个月前

其他发布通道:latest-1 → 1.2.0,release-2.x → 2.2.0,beta → 4.0.2-beta.27,rc → 4.0.2-rc.1。

关于 @eggjs/router 的常见问题

@eggjs/router 是什么?

蛋/可口的路由器中间软件. 提供 REST 资源路径 .

如何安装 @eggjs/router?

在项目目录运行 npm install @eggjs/router,或使用 pnpm add / yarn add / bun add。

@eggjs/router 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@eggjs/router 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@eggjs/router 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.18.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@eggjs/router 可以商用吗?

@eggjs/router 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@eggjs/router 的下载量有多少?

根据 npm 官方下载统计,@eggjs/router 在 2026/10/13 – 2026/11/11 这 30 天内被下载 96,197 次,日均约 3,207 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@eggjs/router 还在维护吗?

最新版本 4.1.0 发布于 2026/10/07(1 个月前);至今共发布 68 个版本,其中过去 12 个月发布了 33 个;首次发布于 2019/01/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。