【决战Koa之巅-4】求你了,花三分钟看一看路由吧!

202 阅读1分钟

一、什么是路由?

路由是引导、匹配之意。
是匹配 URL 到相应处理程序的活动 --- 引用 Python 官网的描述

简单来说,就是让你的请求到达指定的处理代码段。

二、自己写一个路由

在中间件中,if...else 嵌套即可

const koa=require('koa');
const app=new koa();

app.use( async (ctx)=>{
  const {url} = ctx
  if(url === "/404"){
    ctx.body = '404 - node found.'
  }else{
    ctx.body = 'Hello world.'
  }
})

app.listen(3000,()=>{
  console.log('启动成功!http://localhost:3000')
});

正常路由:

image.png

404路由:

image.png

三、三方中间件库

1. koa-router

遵循之前中间件选取原则,先来看看目前网上文章普遍Ω XCVSAWER3T4561流行的 koa-router

能否覆盖需求?

社区活跃度?

几乎没有更新了,最近一次代码提交在2019年

image.png 那就不推荐用这个

2. @koa/router

forked from koa-router,使用方式一样,算是站在巨人的肩膀上

能否覆盖需求?

社区活跃度?

非常棒,上一次提交本月内

Github:github.com/koajs/route…

image.png

文档及 Demo 是否齐全

比较齐全,与 koa-router 共享文档,理论上 koa-router 都 api 都可以使用

中间件体积

image.png

可以看见,最新的10.1.0版本体积总共24KB,符号要求

使用示例

npm i @koa/router
const koa=require('koa');
const Router = require('@koa/router')
const app=new koa();
const router = new Router()
router.get('/', async(ctx, next)=>{
  ctx.body = 'Hello world!'
})
router.get('/404', async(ctx, next)=>{
  ctx.body = '404 - node found.'
})

app.use(router.routes())
app.listen(3000,()=>{
  console.log('启动成功!http://localhost:3000')
});