koa 路由以及动态路由

1、引入Koa类和路由类
	const Koa=require('koa');
	const Router=require('koa-router');
	
2、实例化两个类
	const app=new Koa();
	const router=new Router();
	
3、启动路由及其方法
	app.use(router.routes())
    .	use(router.allowedMethods());

4、创建get路由
	方式一:链式创建多个路由
		router.get('/x',async(ctx,next)=>{
		    ...
		}).get('/xx',async(ctx,next)=>{
		 	...
		})
	方式二:单独创建
		router.get('/x',async(ctx,next)=>{
		    ...
		})
		...
5、动态路由(即,一个路由的路径中有可以任意变化的值,但都是一个路由)
	router.get('/x/:xx',async(ctx,next)=>{
		    ctx.params.xx即可获取动态路由url上变量的值
		})

代码示例:

const Koa=require('koa');
const Router=require('koa-router');

const app=new Koa();
const router=new Router();

app.use(router.routes())
    .use(router.allowedMethods());


router.get('/',async(ctx,next)=>{
    ctx.body='hello';
}).get('/news',async(ctx,next)=>{
    ctx.body='news';
})

router.get('/msg',async(ctx,next)=>{
    ctx.body=ctx.query.id;
})

//动态路由
router.get('/home/:aid/:aic',async(ctx,next)=>{
    ctx.body=ctx.params.aid+ctx.params.aic;
})

app.listen(3000,()=>{
    console.log('this koa server is running at http://localhost:3000/');
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章