Koa2学习(六)使用koa-router

配置简单路由

  1. 引入中间件
  2. 配置需要的路由
  3. 通过app.use注册路由
const Koa = require('koa')
const app = new Koa()
// 引入koa-router并对其实例化
const router = require('koa-router')()
// 配置get路由
router.get('/get', function (ctx, next) {
ctx.body = 'this is a get response!'
})
// 配置post路由
router.post('/post', function (ctx, next) {
ctx.body = 'this is a post response!'
})
// 注册路由
app.use(router.routes(), router.allowedMethods()) app.listen(8000) module.exports = app

请求后我们可以看到结果:

GET:

this is a get response!

POST:

this is a post response!

这是最基本的路由配置,虽然所有的路由都可以通过这样的方式配,但是在实际项目中,这样的代码后期会极其难以维护,我们还有更优雅的方式去配置你的路由。

配置路由层级

router.prefix

koa-router提供一种router.prefix方法,此方法对于某一个router来说,是一个全局配置,此router的所有路径都会自动被添加该前缀。

const Koa = require('koa')
const app = new Koa()
// 引入koa-router
const router = require('koa-router')
// 这两行代码等同于 const router1 = require('koa-router')()
const router1 = new router()
// 为router1配置路由前缀
router1.prefix('/pre')
router1.get('/get', function (ctx, next) {
ctx.body = 'this is a get1 response!'
})
// router2不配置路由前缀
const router2 = new router()
router2.get('/get', function (ctx, next) {
ctx.body = 'this is a get2 response!'
})
// 注册路由
app.use(router1.routes(), router1.allowedMethods())
app.use(router2.routes(), router2.allowedMethods()) app.listen(8000) module.exports = app

我们用浏览器访问,发现get1的路由是/pre/get1,get2的路由是/get2:

localhost:8000/pre/get

this is a get1 response!

localhost:8000/get

this is a get2 response!

router.use

使用router.use方法,同样的能够为路由分层,并且不会因为忽略了prefix的全局配置造成一些不必要的失误,

推荐使用这一种方法为路由分层

const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')
// 定义子路由
const router_children = new router()
router_children.get('/get', function (ctx, next) {
ctx.body = 'this is a get response from router.use!'
})
// 根路由
const router_root = new router()
// 在根路由中注册子路由
router_root.use('/root', router_children.routes(), router_children.allowedMethods())
// 在app中注册根路由
app.use(router_root.routes(), router_root.allowedMethods())
app.listen(8000) module.exports = app

浏览器访问localhost:8000/root/get:

this is a get response from router.use!

动态路由参数

类似于vue-router,可以将参数直接以 /path/parma 的形式传递参数。

路由的param参数通过ctx.params获取。

const Koa = require('koa')
const app = new Koa()
const koa_router = require('koa-router')
const router = new koa_router()
router.get('/:category/:page/:id', function (ctx, next) {
ctx.body = ctx.params
})
app.use(router.routes(), router.allowedMethods())
app.listen(8000) module.exports = app

浏览器访问localhost:8000/story/99/195c6f5b-2f71-4412-9634-bfd05f80c7c4

{
"category": "story",
"page": "99",
"id": "195c6f5b-2f71-4412-9634-bfd05f80c7c4"
}

分割路由文件

当我们的项目越做越大时,可能最终会有成百上千个路由,如果这些路由全部写在一个文件下面,对后期的维护将是一个极大的考验。

因此为了让我们的代码具备高可维护性,可拓展性,我们最好对路由进行切割并分层,我们借助node.jsfs模块对文件操作能够很轻易的实现路由切割。

如果你对fs模块还不太了解,请先自行学习此模块。

app.js:

const Koa = require('koa')
const app = new Koa()
const routes = require('./routes')
app.use(routes.routes(), routes.allowedMethods())
app.listen(8000) module.exports = app

此段用来引入并注册routes文件夹下的index.js文件。

routes/index.js:

const router = require('koa-router')()
const fs = require('fs')
const path = require('path') const files = fs.readdirSync(__dirname)
files
.filter(file => ~file.search(/^[^\.].*\.js$/))
.forEach(file => {
const file_name = file.substr(0, file.length - 3);
const file_entity = require(path.join(__dirname, file));
if (file_name !== 'index') {
router.use(`/${file_name}`, file_entity.routes(), file_entity.allowedMethods())
}
}) module.exports = router

这一段代码特别关键,用来引入并注册所有同级目录下的js文件(此目录下的js文件都是路由文件),并为他们配上以文件名命名的层级前缀。

routes/demo.js:

const router = require('koa-router')()

router.get('/', function (ctx, next) {
ctx.body = 'demo'
}) router.get('/child', function (ctx, next) {
ctx.body = 'demo child'
}) module.exports = router

这个就是业务的示例文件,没什么特别的。需要新增路由只需要新增此类文件即可。

通过浏览器进行访问测试

localhost:8000/demo/child

demo child

localhost:8000/demo

demo

好了,路由已经被成功分割。

Koa2学习(六)使用koa-router的更多相关文章

  1. Koa2学习(九)与mongoDB交互

    Koa2学习(九)与mongoDB交互 数据库下载与安装 windows下载地址:http://dl.mongodb.org/dl/win32/x86_64 linux下载地址:https://www ...

  2. Koa2学习(八)使用session

    Koa2学习(八)使用session koa2框架不提供session的处理方法,这里我们需要借助一个第三方中间件koa-session来处理session. 先安装插件: $ npm i koa-s ...

  3. Koa2学习(七)使用cookie

    Koa2学习(七)使用cookie Koa2 的 ctx 上下文对象直接提供了cookie的操作方法set和get ctx.cookies.set(name, value, [options])在上下 ...

  4. Koa2学习(五)中间件

    Koa2学习(五)中间件 Koa2通过app.use(function)方法来注册中间件. 所有的http请求都会依次调用app.use()方法,所以中间件的使用顺序非常重要. 中间件的执行顺序 官方 ...

  5. Koa2学习(四)POST请求

    Koa2学习(四)POST请求 接受请求 POST请求的数据实体,会根据数据量的大小进行分包传送. 当node.js后台收到post请求时,会以buffer的形式将数据缓存起来.Koa2中通过ctx. ...

  6. Koa2学习(三)GET请求

    Koa2学习(三)GET请求 GET请求是前后端交互最常用的请求之一,常常用来进行查询操作. 那么Koa是如何接收并处理GET请求呢? 创建一个服务 // 引入Koa const Koa = requ ...

  7. Koa2学习(一)环境搭建

    Koa2学习(一)环境搭建 koa2脚手架 koa2服务安装 koa2-generator目录结构 什么是 Koa2 koa 是由 Express 原班人马打造的,致力于成为一个更小.更富有表现力.更 ...

  8. day 84 Vue学习六之axios、vuex、脚手架中组件传值

    Vue学习六之axios.vuex.脚手架中组件传值   本节目录 一 axios的使用 二 vuex的使用 三 组件传值 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 axios的 ...

  9. Hbase深入学习(六) Java操作HBase

    Hbase深入学习(六) ―― Java操作HBase 本文讲述如何用hbase shell命令和hbase java api对hbase服务器进行操作. 先看以下读取一行记录hbase是如何进行工作 ...

随机推荐

  1. Python中 模块、包、库

    模块:就是.py文件,里面定义了一些函数和变量,需要的时候就可以导入这些模块. 包:在模块之上的概念,为了方便管理而将文件进行打包.包目录下第一个文件便是 __init__.py,然后是一些模块文件和 ...

  2. 牛客网 牛可乐发红包脱单ACM赛 C题 区区区间间间

    [题解] 我想到了两种解法. 一种是扫描线+线段树+单调栈. 另一种方法是O(n)的,比较巧妙. 考虑每个数在哪些区间可以作为最小数.最长的区间就是它向左右走,直到有数字比它小,这个可以用单调栈维护. ...

  3. 算法导论 第九章 中位数和顺序统计量(python)

    第i个顺序统计量:该集合中第i小的元素(建集合排序后第i位 当然算法可以不排序) 中位数:集合中的中点元素 下中位数 上中位数 9.1最大值和最小值 单独的max或min每个都要扫一遍 n-1次比较 ...

  4. 大数据学习——Linux-SSH报错:Could not resolve hostname centos02: Temporary failure in name resolution

    https://blog.csdn.net/mcb520wf/article/details/83303792 随笔异常 ssh: Could not resolve hostname centos0 ...

  5. vsftpd系统用户配置详解

    1.安装yum -y install pam pam-devel db4 de4-devel db4-uitls db4-tclyum -y install vsftpd 新建vsftpd系统用户:u ...

  6. 洛谷P1244 青蛙过河

    P1244 青蛙过河 362通过 525提交 题目提供者该用户不存在 标签 难度普及- 时空限制1s / 128MB 提交 讨论 题解 最新讨论更多讨论 题目什么意思 题目看不懂啊 题目描述 有一条河 ...

  7. Tsinghua OJ Zuma

    Description Let's play the game Zuma! There are a sequence of beads on a track at the right beginnin ...

  8. Codevs 1695 Windows2013

    时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold   题目描述 Description 话说adamyi编的Windows 2013超时了(- -!),所以他不得不在自 ...

  9. 转载:用vector保存对象时保存指针的优点, 以及reserve的使用

    #include <vector> #include <stdio.h> class A { public: A() { printf("A()/n"); ...

  10. iOS tableview上textView在编辑状态时,tableview自动上移的功能

    在viewcognroller中,添加tableview时, tableview中cell上的textField如果吊起键盘时,tableview时可以自动上移,但是如果是textView吊起键盘,t ...