一、资源路由
对于一套业务,涉及到CRUD,若将访问的地址全部写入路由组件。代码会很冗余
使用资源路由即可解决这个问题。可见官网
例、对于一个app/controller/posts.js,涉及到很多的业务。可使用资源路由简化代码。
1、创建一个posts.js
// app/controller/posts.js// 列表页
async index () {
this.ctx.body = 'index'
};
// 新增表单页
async new () {
this.ctx.body = 'new'
};
// 新增逻辑
async create () {
this.ctx.body = 'create'
};
// 详情页
async show () {
this.ctx.body = 'show'
};
// 编辑表单页
async edit () {
this.ctx.body = 'edit'
};
// 更新逻辑
async update () {
this.ctx.body = 'update'
};
// 删除逻辑
async destroy () {
this.ctx.body = 'destroy'
};
2、设置路由
路由一行代码,即可解决
// app/router.js module.exports = app => { const { router, controller } = app; router.resources('posts', '/post', controller.posts); };
//第一个posts为名称,第二个'/post'为匹配的路由地址
3、页面访问
例如 http://127.0.0.1:7001/post或http://127.0.0.1:7001/post/new
下表是访问方式、访问地址、行为等一些对等关系
二、路由分组
上面写的是一个posts.js,使用了资源路由。若controller中有多个js文件,则可以使用路由分组。
1、在controller文件夹下创建news.js和admin.js两个文件,都各自包含了功能模块(可参考上面的posts)
2、在app/router目录下创建两个路由,分别管理controller下面的js文件
3、最后将app/router中的分路由统一由app/router.js管理。
// app/router.js module.exports = app => { require('./router/news')(app); require('./router/admin')(app); }; // app/router/news.js module.exports = app => { router.resources('news', '/api/news', controller.news) }; // app/router/admin.js module.exports = app => { router.resources('admin', '/api/admin', controller.admin) };
地址访问:
http://127.0.0.1:7001/api/admin
或http://127.0.0.1:7001/api/admin/new