koa-router 7中文

Koa-router 7

  • Express风格的路由 app.get, app.put, app.post, 等等
  • 命名URL参数
  • 命名路由由URL生成
  • Responds to OPTIONS requests with allowed methods.
  • 支持 405 Method Not Allowed501 Not Implemented.
  • 多路由中间件
  • 多路由
  • 嵌套路由
  • ES7 async/await 支持

API Reference

Router ⏏

类型: 导出类

new Router([opts])

创建一个新的路由

Param参数 Type类型 Description描述
[opts] Object
[opts.prefix] String prefix router paths 路由前缀路径

Example
Basic usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/', function (ctx, next) {
// ctx.router available
});
app
.use(router.routes())
.use(router.allowedMethods())

router.get|put|post|patch|delete|del ⇒ Router

verb:动词

创建 router.verb() 方法, 其中动词是诸如router.get() or router.post()之类的HTTP动词之一。

使用router.verb()将URL与回调函数或控制器进行匹配,其中动词是诸如router.get()或router.post()之类的HTTP动词之一。

另外, router.all() 可以匹配所有路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
router
.get('/', function (ctx, next) {
ctx.body = 'Hello World!';
})
.post('/users', function (ctx, next) {
// ...
})
.put('/users/:id', function (ctx, next) {
// ...
})
.del('/users/:id', function (ctx, next) {
// ...
})
.all('/users/:id', function (ctx, next) {
// ...
});

当一个路由匹配时,其路径在ctx._matchedRoute可用,如果命名,则名称可在ctx._matchedRouteName

路由路径将使用 path-to-regexp.转换为正则表达式

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

Named routes 命名路由

路由可以配置名称。这样可以在开发过程中轻松生成URL或重命名URL。

1
2
3
4
5
6
router.get('user', '/users/:id', function (ctx, next) {
// ...
});
router.url('user', 3);
// => "/users/3"

Multiple middleware 多中间件

一个路由可以给多个中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
router.get(
'/users/:id',
function (ctx, next) {
return User.findOne(ctx.params.id).then(function(user) {
ctx.user = user;
next();
});
},
function (ctx) {
console.log(ctx.user);
// => { id: 17, name: "Alex" }
}
);

Nested routers

支持嵌套路由

1
2
3
4
5
6
7
8
9
const forums = new Router();
const posts = new Router();
posts.get('/', function (ctx, next) {...});
posts.get('/:pid', function (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());

Router prefixes

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

1
2
3
4
5
6
var router = new Router({
prefix: '/users'
});
router.get('/', ...); // responds to "/users"
router.get('/:id', ...); // responds to "/users/:id"

URL parameters

路由参数被捕获并添加到ctx.params.

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

The path-to-regexp module is used to convert paths to regular expressions.

Kind: Router的实例属性

Param Type Description
path String
[middleware] function route middleware(s)
callback function route callback

router.routes ⇒ function

返回匹配到的路由所调用的中间件

Kind: Router的实例属性

router.use([path], middleware) ⇒ Router

Use given middleware.

使用指定的中间件

中间件按照由.use()定义的顺序运行。它们被按顺序调用,第一个中间件开始,以中间件堆栈的方式依次向下执行。

Kind: Router的实例方法

Param Type
[path] String
middleware function
[…] function

Example

1
2
3
4
5
6
7
8
9
10
11
12
// 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());

router.prefix(prefix) ⇒ Router

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

Kind: Router的实例方法

Param Type
prefix String

Example

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

router.allowedMethods([options]) ⇒ function

Returns separate middleware for responding to OPTIONS requests with an Allow header containing the allowed methods, as well as responding with 405 Method Not Allowed and 501 Not Implemented as appropriate.

Kind: instance method of Router

Param Type Description
[options] Object
[options.throw] Boolean throw error instead of setting status and header 抛出错误而不是设置status和header
[options.notImplemented] function throw the returned value in place of the default NotImplemented error 抛出返回值代替默认NotImplemented error
[options.methodNotAllowed] function throw the returned value in place of the default MethodNotAllowed error 抛出返回值代替默认NotImplemented error

Example

1
2
3
4
5
6
7
8
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(router.routes());
app.use(router.allowedMethods());

Example with Boom

1
2
3
4
5
6
7
8
9
10
11
12
13
const Koa = require('koa');
const Router = require('koa-router');
const Boom = require('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()
}));

router.redirect(source, destination, code) ⇒ Router

Redirect source to destination URL with optional 30x status code.

Both source and destination can be route names.

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

This is equivalent to:

1
2
3
4
router.all('/login', function (ctx) {
ctx.redirect('/sign-in');
ctx.status = 301;
});

Kind: instance method of Router

Param Type Description
source String URL or route name.
destination String URL or route name.
code Number HTTP status code (default: 301).

router.route(name) ⇒ Layer | false

Lookup route with given name.

Kind: instance method of Router

Param Type
name String

router.url(name, params) ⇒ String | Error

Generate URL for route. Takes a route name and map of named params.

Kind: instance method of Router

Param Type Description
name String route name
params Object url parameters

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
router.get('user', '/users/:id', function (ctx, next) {
// ...
});
router.url('user', 3);
// => "/users/3"
router.url('user', { id: 3 });
// => "/users/3"
router.use(function (ctx, next) {
// redirect to named route
ctx.redirect(ctx.router.url('sign-in'));
})

router.param(param, middleware) ⇒ Router

Run middleware for named route parameters. Useful for auto-loading or validation.

Kind: instance method of Router

Param Type
param String
middleware function

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
router
.param('user', function (id, ctx, next) {
ctx.user = users[id];
if (!ctx.user) return ctx.status = 404;
return next();
})
.get('/users/:user', function (ctx) {
ctx.body = ctx.user;
})
.get('/users/:user/friends', function (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(path, params) ⇒ String

Generate URL from url pattern and given params.

Kind: static method of Router

Param Type Description
path String url pattern
params Object url parameters

Example

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

Contributing

Please submit all issues and pull requests to the alexmingoia/koa-router repository!

Tests

Run tests using npm test.

Support

If you have any problem or suggestion please open an issue here.