其实,router这个是一个很重要的内容,用户进行url访问就可以更好的使用
app.use(async (ctx,next)=>{
if (ctx.path === '/') {
ctx.body = 'we are at home!';
} else {
await next;
}
})
app.use(async (ctx,next)=>{
if (ctx.path === '/404') {
ctx.body = 'page not found';
} else {
await next;
}
})
const Koa = require('koa')
const fs = require('fs')
const app = new Koa()
const Router = require('koa-router')
let home = new Router()
// 子路由1
home.get('/', async ( ctx )=>{
let html = `
<ul>
<li><a href="/page/helloworld">/page/helloworld</a></li>
<li><a href="/page/404">/page/404</a></li>
</ul>
`
ctx.body = html
})
// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
ctx.body = 'helloworld page!'
})
// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('[demo] route-use-middleware is starting at port 3000')
})
router
.get('/', async (ctx, next) => {
ctx.body = 'Hello World!';
})
.post('/users', async (ctx, next) => {...})
.put('/users/:id', async (ctx, next) => {...})
.del('/users/:id', async (ctx, next) => {...})
.all('/users/:id', async (ctx, next) => {...})
router.all()用于表示上述所有的动词方法
router.get('/', async (ctx,next) => {
ctx.body = 'Hello World!';
});
上面代码中,router.get方法的第一个参数是根路径,第二个参数是对应的函数方法。
我们可以通过ctx.params得到URL参数
router.get('/:category/:title', function (ctx, next) {
console.log(ctx.params);
// => { category: 'programming', title: 'how-to-node' }
});
这里有个中路由中间件汇集https://cnodejs.org/topic/57838dfaee5f048d54f90877
参考:
https://chenshenhai.github.io/koa2-note/note/route/koa-router.html
https://github.com/minghe/koa-book/blob/master/start/router.md
转载:https://www.jianshu.com/p/0d59a4270997