寫了一個基於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 獲取
是不是覺得很簡單~