Router middleware for koa
npm install --save koa-qc-router
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`)
})
/*
Explained ①:
Group name and controller name capitalization.
{
'Group Name' : [
['Controller name', Controller file module ]
]
}
*/
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`)
})
/*
Explained ②:
Route mapping relationship, the controller module to be mapped
[
['news' , 'index/news/index']
]
*/
Take index/index/info
as an example, create it under the project path.
1, create a grouping unit folder Index
, pay attention to the first letter capitalization
2, create a controller file Index.js
under the group, the first letter is capitalized
3, add the info
method in the controller file
// Index.js
class Index {
constructor(ctx) {
this.ctx = ctx
}
async info() {
//...
}
}
module.exports = Index
// http://127.0.0.1:3000 => group => Index control => Index action => index
// When no mapping is set
// http://127.0.0.1:3000/user => group => User control => Index action => index
// http://127.0.0.1:3000/user/info => group => User control => Info action => index
// http://127.0.0.1:3000/user/info/upload => group => User control => Info action => upload
//When there is a mapping relationship
[
['news' , 'index/news/info']
]
// http://127.0.0.1:3000/news => group => Index control => News action => info
// When no mapping is set
// http://127.0.0.1:3000/user/info/upload/id/1/type/1 => ctx.query.id ctx.query.type
//When there is a mapping relationship
[
['news', 'index/news/index']
]
// http://127.0.0.1:3000/news/id/1 => ctx.query.id