# @eggjs/router 中文文档

规范地址：https://npmcn.com/package/%40eggjs/router/

版本：4\.1\.0
npm 元数据更新时间：2026-10-07T08:20:20.772Z
中文译文更新时间：2026-11-13T09:00:27.681Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40eggjs/router
原文对照：https://npmcn.com/package/%40eggjs/router/?lang=original
项目主页：https://github.com/eggjs/egg/tree/next/packages/router
源码仓库：https://github.com/eggjs/egg

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：82.4 kB，12 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.18\.0
- 运行依赖：8 个
- 首次发布：2019-01-30T02:44:31.729Z
- 最新版本发布：2026-10-07T08:20:20.284Z
- 近 30 天下载量：96197（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：68（近 12 个月 33 个）

## 中文简介

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

## 安装

```sh
npm install @eggjs/router
```

也可以使用：`pnpm add @eggjs/router`、`yarn add @eggjs/router`、`bun add @eggjs/router`

## README

# @eggjs/路由器

[![NPM version](https://img.shields.io/npm/v/@eggjs/router.svg?style=flat-square)](https://npmjs.org/package/@eggjs/router) [![NPM download](https://img.shields.io/npm/dm/@eggjs/router.svg?style=flat-square)](https://npmjs.org/package/@eggjs/router) [![Known Vulnerabilities](https://snyk.io/test/npm/@eggjs/router/badge.svg?style=flat-square)](https://snyk.io/test/npm/@eggjs/router) [![Node.js Version](https://img.shields.io/node/v/@eggjs/router.svg?style=flat)](https://nodejs.org/en/download/) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com/) ![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/eggjs/router)

路由器核心组件用于 [鸡蛋.js](https://github.com/eggjs)。 。 。 .

> **此寄存器为 [旋转道](https://github.com/alexmingoia/koa-router)。 。 。 .** 带有一些额外特征. 感谢@alexmingoia和原始团队的出色工作.

## API 参考

-   [@eggjs/路由器](https://npmcn.com/package/%40eggjs/router/#readme-eggjsrouter)
    -   [API 参考](https://npmcn.com/package/%40eggjs/router/#readme-api-reference)
        -   [路由器QQ](https://npmcn.com/package/%40eggjs/router/#readme-router-)
            -   [新建路由器( \[opts\] )](https://npmcn.com/package/%40eggjs/router/#readme-new-routeropts)
            -   [路由器.get|put|post|patch|delelete|del⇒路由器](https://npmcn.com/package/%40eggjs/router/#readme-routergetputpostpatchdeletedel--router)
            -   [命名路线](https://npmcn.com/package/%40eggjs/router/#readme-named-routes)
            -   [多个中间软件](https://npmcn.com/package/%40eggjs/router/#readme-multiple-middleware)
        -   [嵌入路由器](https://npmcn.com/package/%40eggjs/router/#readme-nested-routers)
            -   [路由器前缀](https://npmcn.com/package/%40eggjs/router/#readme-router-prefixes)
            -   [URL 参数](https://npmcn.com/package/%40eggjs/router/#readme-url-parameters)
            -   [路由器. routes qq 函数](https://npmcn.com/package/%40eggjs/router/#readme-routerroutes--function)
            -   [路由器.use(\[路径\],中间软件) QQ路由器](https://npmcn.com/package/%40eggjs/router/#readme-routerusepath-middleware--router)
            -   [路由器.prefix(前缀) QQ路由器](https://npmcn.com/package/%40eggjs/router/#readme-routerprefixprefix--router)
            -   [路由器.allowd Methods (\[选项\]) QQ函数](https://npmcn.com/package/%40eggjs/router/#readme-routerallowedmethodsoptions--function)
            -   [路由器.rediction(来源,目的地,\[代码\]) QQ路由器](https://npmcn.com/package/%40eggjs/router/#readme-routerredirectsource-destination-code--router)
            -   [路由器.route(名称) QQ 层 QQ 假](https://npmcn.com/package/%40eggjs/router/#readme-routerroutename--layer--false)
            -   [路由器.url(名称,参数,\[选项\]) QQ String QQ出错](https://npmcn.com/package/%40eggjs/router/#readme-routerurlname-params-options--string--error)
            -   [路由器.param( param, 中间软件) QQ 路由器](https://npmcn.com/package/%40eggjs/router/#readme-routerparamparam-middleware--router)
            -   [路由器.url(路径,参数\[,选项\]) QQ String](https://npmcn.com/package/%40eggjs/router/#readme-routerurlpath-params--options--string)
    -   [测试](https://npmcn.com/package/%40eggjs/router/#readme-tests)
    -   [V3 正在中断更改](https://npmcn.com/package/%40eggjs/router/#readme-breaking-changes-on-v3)
    -   [许可证](https://npmcn.com/package/%40eggjs/router/#readme-license)
    -   [贡献者](https://npmcn.com/package/%40eggjs/router/#readme-contributors)

### 路由器QQ

**仁爱**: 导出类别

#### 新建路由器( \[opts\] )

创建新路由器 .

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

**示例** 基本用途:

```ts
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()` 可以用来匹配所有方法.

```ts
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`

路由路径将使用 [路径到备忘](https://github.com/pillarjs/path-to-regexp)。 。 。 .

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

#### 命名路线

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

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

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

#### 多个中间软件

多个中间软件可能给出:

```ts
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" }
  },
);
```

### 嵌入路由器

支持嵌入路由器 :

```ts
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());
```

#### 路由器前缀

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

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

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

#### URL 参数

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

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

这个 [路径到备忘](https://github.com/pillarjs/path-to-regexp) 模块是 用于将路径转换为正则表达式.

**仁爱**: 实例财产 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

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

#### 路由器. 路由器 qq `function`

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

**仁爱**: 实例财产 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

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

使用给定的中间软件 .

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

**仁爱**: 实例方法 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

| 参数 | 类型 |
| --- | --- |
| \[路径\] | `String` |
| 中间软件 | `function` |
| \[...\] | `function` |

**示例**

```ts
// 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](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

| 参数 | 类型 |
| --- | --- |
| 前缀 | `String` |

**示例**

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

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

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

**仁爱**: 实例方法 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

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

**示例**

```ts
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());
```

**示例 [轰](https://github.com/hapijs/boom)**

```ts
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` 可以是路由名称.

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

这相当于:

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

**仁爱**: 实例方法 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| 来源 | `String` | URL或路由名称. |
| 目标 | `String` | URL或路由名称. |
| \[编码\] | `Number` | HTTP 状态代码( 默认: 301). |

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

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

**仁爱**: 实例方法 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

| 参数 | 类型 |
| --- | --- |
| 名称 | `String` |

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

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

**仁爱**: 实例方法 `[Router](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

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

**示例**

```ts
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](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

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

**示例**

```ts
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](https://npmcn.com/package/%40eggjs/router/#readme-exp_module_egg-router--Router)`

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

**示例**

```ts
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 支持

## 许可证

[麻省理工学院](https://npmcn.com/package/%40eggjs/router/LICENSE)

## 贡献者

[![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)

制造的 [贡献者-img](https://contrib.rocks/)。 。 。 .

## 常见问题

### @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 和提交记录判断。

