写了一个基于koa2的路由中间件,有控制器与方法的概念,有兴趣的小伙伴可以安装玩一下。
传送门 https://npm.taobao.org/package/koa-qc-router
安装
npm install koa-qc-router
基本用法
/*
URL解析规则
/index/user/info -> /分组名/控制器/方法名
1、/ 会默认解析成 /index/index/index
2、/user 会解析成 /user/index/index
3、/user/info 会解析成 /user/info/index
注:设置了路由映射,根据映射后的路由解析
*/
//例1
const Koa = require('koa') // koa v2.x
const path = require('path')
const router = require('koa-qc-router')
var app = new Koa()
app.use(router(
// ①
{
'Index' : [
['Index', require(`./app/Index/Index`)]
]
}
))
app.use(async (ctx, next) => {
//404
console.log(`${ctx.group}/${ctx.control}/${ctx.action} is not find`)
})
/*
注①:
{
'分组名' : [
['控制器名', 控制器模块 ]
]
}
//控制器路径推荐使用 App目录->分组目录->控制器文件
//这样的目录结构层次分明
*/
//例2
const Koa = require('koa') // koa v2.x
const path = require('path')
const router = require('koa-qc-router')
var app = new Koa()
app.use(router(
{
'Index' : [
['Index', require(`./app/Index/Index`)]
]
},
// ②
[
['news' , 'index/index/news'],
['news/info' , 'index/index/info']
]
))
app.use(async (ctx, next) => {
//404
console.log(`${ctx.group}/${ctx.control}/${ctx.action} is not find`)
})
/*
注②:
路由映射
规则 路由 -> 映射路由
确保映射的路由的控制器模块已引入
[
['news' , 'index/news/index']
]
*/
// 以下面为例
app.use(router(
{
'Index' : [
['Index', require(`./app/Index/Index`)],
['News', require(`./app/Index/News`)],
]
},
[
['news' , 'index/news/info']
]
))
/*
参数讲解
1、第一个参数引入了用到的控制器模块 Index.js News.js
2、第二个参数设置了路由映射关系 访问 /news 映射到 /index/news/info
为了使项目目录更清晰,推荐使用以下目录结构
app项目目录
分组文件夹
对应控制器模块的视图文件夹
控制器文件
所以上面例子可以创建目录结构为
index.js 运行文件
app文件夹
Index 分组文件夹
Index 对应控制器模块存放视图的文件夹
News 对应控制器模块存放视图的文件夹
Index.js 控制器文件
News.js 控制器文件
注意:分组文件夹 与 控制器模块文件 首字母需大写
*/
// 控制器模块写法,以 /index/user/info 为例,分组为Index , 控制器模块为 User 方法名为 info
class User {
//构造函数接收ctx对象,方便此类中的其他方法调用
constructor(ctx) {
this.ctx = ctx
}
async info() {
//...
}
}
module.exports = User
//如果访问 /index/user/upload,直接在上面类中加入upload方法即可,一切如此简单
GET参数
访问 /news/info/index/id/1/type/2 这样路由时,除了分组,控制器,方法外会把后面的路由解析成GET参数
// 访问 /news/info/index/id/1/type/2
class Info{
constructor(ctx) {
this.ctx = ctx
}
async index() {
let id = this.ctx.query.id
let type = this.ctx.query.type
}
}
module.exports = Info
当设置了路由映射关系时,按照设置的路由名称计算。
[
['news' , 'index/news/index']
]
// 访问 /news/id/1/type/2
//也可以通过 this.ctx.id this.ctx.type 获取
是不是觉得很简单~