一、基本用法
var app = require('koa')(); var router = require('koa-router')(); router.get('/', function *(next) {...}); app .use(router.routes()) .use(router.allowedMethods());
二、router.get|put|post|patch|delete
router .get('/', function *(next) { this.body = 'Hello World!'; }) .post('/users', function *(next) { // ... }) .put('/users/:id', function *(next) { // ... }) .del('/users/:id', function *(next) { // ... });
三、多个中间件例子
router.get( '/users/:id', function *(next) { this.user = yield User.findOne(this.params.id); yield next; }, function *(next) { console.log(this.user); // => { id: 17, name: "Alex" } } );
四、嵌套路径
var forums = new Router(); var posts = new Router(); posts.get('/', function *(next) {...}); posts.get('/:pid', function *(next) {...}); forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods()); // responds to "/forums/123/posts" and "/forums/123/posts/123" app.use(forums.routes());
五、路由前缀
var router = new Router({ prefix: '/users' }); router.get('/', ...); // responds to "/users" router.get('/:id', ...); // responds to "/users/:id"
六、重定向
router.redirect('/login', 'sign-in');
还有另外一种写法
router.all('/login', function *() { this.redirect('/sign-in'); this.status = 301; });
七、router.url(name, params)
router.get('user', '/users/:id', function *(next) { // ... }); router.url('user', 3); // => "/users/3" router.url('user', { id: 3 }); // => "/users/3"