本文主要是介绍路由的作用,以及Koa中路由中间件的使用,一些高级用法,实用技巧等。什么是路由?HandlingdifferentURLsHandlingdifferentHTTPmethods(GET,POST,PUT,DELETE,PATCH,OPTIONS)解析URL上的参数在HTTP协议中,路由可以理解为根据不同的HTTP请求返回不同的响应;如果没有路由会怎样?请看下面的代码:constKoa=require('koa')constapp=newKoa()app.use(asyncctx=>{ctx.body='helloworld'})app.listen(3000)通过Postman访问3000端口,无论是哪种HTTP方式,不同的URL,都会返回相同的内容。这种没有路由的WEB服务几乎做不了什么有价值的事情。自定义Koa路由中间件路由,最基本的功能是处理不同的URL,不同的HTTP方法,解析URL参数处理不同的HTTP方法constKoa=require('koa')constapp=newKoa()app.use(asyncctx=>{if(ctx.method==='GET'){ctx.body='GET请求'}elseif(ctx.method==='POST'){ctx.body='POST请求'}elseif(ctx.method==='PUT'){ctx.body='PUTrequest'}elseif(ctx.method==='DELETE'){ctx.body='DELETErequest'}})app.listen(3000)处理不同的URLapp.use(asyncctx=>{if(ctx.method==='GET'){switch(ctx.url){case'/':ctx.body='Home';break;case'/users':ctx.body='用户列表';break;case'/articles':ctx.body='文章列表';休息;default:ctx.status=404}}})解析URL参数app.use(asyncctx=>{if(ctx.method==='GET'){//根据用户ID获取用户信息if(/^\/users\/(\w+)$/.test(ctx.url)){returnctx.body=`UserIDis:${RegExp.$1}`}ctx.status=404}})上面的演示代码是只是最基本的路由概念,完整的路由逻辑需要考虑的实际情况比较复杂。建议有一个优秀优雅的程序,需要独立维护的代码越少越好嘛,别做重新发明轮子的事,人生有限!使用官方中间件或者其他优秀的第三方中间件可以节省开发时间,提高开发效率!koa-routerkoa-router基本使用安装yarnaddkoa-router基本使用constKoa=require('koa');constRouter=require('koa-router');constapp=newKoa();constrouter=newRouter();//处理不同的HTTP方法router.get('/users',ctx=>{ctx.body='getuserlist'}).post('/users',ctx=>{ctx.body='创建用户'}).put('/users/:id',ctx=>{//解析URL参数ctx.body=`更新id为${ctx.params.id}的用户`}).delete('/users/:id',ctx=>{//解析URL参数ctx.body=`删除ID为${ctx.params.id}的用户`})//注册路由中间件app.use(router.routes())app.listen(3000)路由前缀配置koa-router的路由前缀,实现路由分类:'/articles'})//文章界面constuserRouter=newRouter({prefix:'/users'})//用户界面articleRouter.get('/',ctx=>ctx.body='articlelist')用户路由器。get('/',ctx=>ctx.body='userlist')app.use(articleRouter.routes())app.use(userRouter.routes())app.listen(3000)使用koa-router的allowedMethods方法,可以实现HTTPOPTIONS方法请求OPTIONS请求可以检测接口支持的请求方法如果有如下代码,通过userRouter.allowedMethods()中间件,让/users接口实现options方法constKoa=require('考阿');constRouter=require('koa-router');constapp=newKoa();constuserRouter=newRouter({prefix:'/users'})//用户界面userRouter.get('/',ctx=>ctx.body='userlist')userRouter.post('/',ctx=>ctx.body='createuser')userRouter.put('/:id',ctx=>ctx.body=ctx.params.id)//使用userRouter.allowedMethods()中间件,让/users接口实现选项方法app.use(userRouter.routes()).use(userRouter.allowedMethods())app.listen(3000)使用postman测试OPOTIONS方法响应头信息中的ALLOW字段,可见/users接口支持的HTTP方法为GET、POST、PUT。如果OPTIONS方法请求接口没有实现方法的HTTP,会返回405状态码。如果OPTIONS方法请求HTTP不支持的方法,会返回501状态码。koa多路由注册技巧在实际项目中,我们的接口是多种多样的,不可能在入口文件中定义所有的路由,并创建一个routes文件夹来存放所有不同的路由接口├──routes(路由)│└──articles.js│└──users.js│└──index.js│├──index.js(入口)│└──package.json//routes/articles.jsconstRouter=require('koa-router')constrouter=newRouter({prefix:'/articles'})router.get('/',ctx=>ctx.body='文章列表')module.exports=router//routes/users.jsconstRouter=require('koa-router')constrouter=newRouter({prefix:'/users'})router.get('/',ctx=>ctx.body='articlelist')module.exports=router//路由/索引.jsconstfs=require('fs');module.exports=(app)=>{//使用fs模块自动读取并注册routes文件夹下的所有路由接口fs.readdirSync(__dirname).forEach(file=>{if(file==='index.js'){返回;}常量路线=require(`./${file}`);app.use(route.routes()).use(route.allowedMethods());});}constKoa=require('koa');constapp=newKoa();constrouting=require('./routes');//一次性注册路由routing(app)app.listen(3000)
