安装
npm install koa-router
使用example
const Koa = require('koa')
// 注意 require('koa-router') 返回的是函数:
const router = require('koa-router')()
const app = new Koa()
// 添加路由
router.get('/', async (ctx, next) => {
ctx.response.body = '<h1>index page</h1>'
})
router.get('/home', async (ctx, next) => {
ctx.response.body = '<h1>HOME page</h1>'
})
router.get('/404', async (ctx, next) => {
ctx.response.body = '<h1>404 Not Found</h1>'
})
// 调用路由中间件
app.use(router.routes())
app.listen(3000, ()=>{
console.log('server is running at http://localhost:3000')
})
路由方法
get | post | put | delete | del | all
*all代表匹配所有,一般放在中间件的末尾
重定向
router.redirect('/login', 'sign-in');
动态路由
router.get('/users/:id', (ctx, next) => {
// ...
});
类似于vue-router,可以将参数直接以 /path/parma 的形式传递参数
路由参数被捕获并添加到ctx.params
router.get('/:category/:title', (ctx, next) => {
console.log(ctx.params);
// => { category: 'programming', title: 'how-to-node' }
});
命名路由
给路由命名,可以在开发过程中生成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" }
}
);
路由嵌套
var forums = new Router();
var 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());
路由前缀
类似于vue-router的子路由
var router = new Router({
prefix: '/users'
});
router.get('/', ...); // responds to "/users"
router.get('/:id', ...); // responds to "/users/:id"