当前位置: 首页 > 工具软件 > koa-ip > 使用案例 >

koa-router基本使用

苏品
2023-12-01

1. 安装

npm i koa-router

2. 导入

const router=require('koa-router')({
	prefix:"/user",    // 路由前缀
});

3. 不同请求

请求方式有get、post、put、del、all,主要使用get和post,all接收所有请求类型,当all和其他类型同时存在时,优先使用其他类型。
// 修改为其他请求类型,只需要将get改成需要的类型即可
router.get('/user',async(ctx,next)=>{
	ctx.body="get请求方式返回数据";
	await next();
})

4. 路由传值

可以接收多个参数,如接收参数id和no
传递的参数会在ctx.params对象中
访问时以 http:localhost:3000/user/111/666这种方式访问

router.get('/user/:id/:no',async(ctx,next)=>{
    ctx.body="Hello World";
    console.log(ctx.params);  //   {id:111,no:666}
    await next();
})

5. 多个中间件

匹配一个路由可以使用多个中间件,但是如果使用ctx.body,后写的会覆盖先写的
router.get('/profile',(ctx,next)=>{
     console.log('中间件1')
   	 next();
},(ctx,next)=>{
    console.log('中间件2')
    ctx.body='单路由对应多中间件';
    next();
})

6. 路由数组

router.get(['/home','/index'],(ctx,next)=>{
   	console.log('多路由对应相同的中间件')
    next();
})

7. * 匹配任意路径 但是优先级比较低 有符合的路径时 就不会被匹配

// *匹配任意url  即可以接收所有get的请求
router.get('/*',async(ctx,next)=>{
  	ctx.body='anything';
  	await next();
})

// 仅仅只有 '/*' 路由时,访问profile路径,返回的是anything */
// 但是 如果有具体的get请求时 优先使用具体的路由  如下:

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

// 当 '/*'和'/profile'同时存在时 当路径是profile时   '/*'不起作用 即返回profile

8. router.use() 路由的前置中间件 可以理解为 所有router所属的路由匹配前都会先执行的中间件 可以进行一些验证

router.use(async (ctx,next)=>{
	console.log("前置中间件 可以用于做验证等");
})
 类似资料: