egg.js定義了快速生成CRUD路由配置的方式,即配置資源路由溯壶,用router.resources來實現(xiàn)
一、router.resources支持的方法
Method | Path | Route Name | Contorller.Action |
---|---|---|---|
GET | /user | 默認 | app.contorllers.user.index |
GET | /user/new | 新增業(yè)務(wù) | app.contorllers.user.new |
GET | /user/:id | 查詢用戶 | app.contorllers.user.show |
GET | /user/id/edit | 編輯用戶 | app.contorllers.user.edit |
POST | /user | 新增用戶 | app.contorllers.user.create |
PUT | /user/:id | 更新用戶 | app.contorllers.user.update |
DELETE | /user/:id | 刪除用戶 | app.contorllers.user.destory |
二、使用
1.配置資源路由戚哎,在router.js文件中增加帖子資源路由
//router.resources()函數(shù)的第一個參數(shù)posts是路由名稱裸诽,第二個參數(shù)/api/posts是請求路徑
router.resources('user', '/user', controller.user);
2.在controller目錄下創(chuàng)建posts.js文件,完整內(nèi)容如下
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
// 用戶列表
async index() {
console.log('>>> index')
this.ctx.body = {
msg: 'ok',
data: '用戶列表'
};
};
// 新增業(yè)務(wù)邏輯
async new() {
console.log('>>> new')
this.ctx.body = {
msg: 'ok',
data: '新增業(yè)務(wù)邏輯'
};
};
// 新增用戶
async create() {
console.log('>>> create')
this.ctx.body = {
msg: 'ok',
data: '新增用戶'
};
};
// 查詢用戶
async show() {
console.log('>>> show')
let id = this.ctx.params.id;
this.ctx.body = {
msg: 'ok',
data: '查詢用戶,id=' + id
};
};
// 編輯用戶
async edit() {
console.log('>>> edit')
let id = this.ctx.params.id;
this.ctx.body = {
msg: 'ok',
data: '編輯用戶,id=' + id
};
};
// 更新用戶
async update() {
console.log('>>> update')
let id = this.ctx.params.id;
this.ctx.body = {
msg: 'ok',
data: '更新用戶, id=' + id
};
};
// 刪除用戶
async destroy() {
console.log('>>> destroy')
let id = this.ctx.params.id;
this.ctx.body = {
msg: 'ok',
data: '刪除用戶, id=' + id
};
};
}
module.exports = PostsController;
三建瘫、路由分組
1崭捍、app文件夾的根目錄下創(chuàng)建 router 文件夾,在router文件夾里新建一個路由模塊
2啰脚、在router下新建user.js殷蛇,將user相關(guān)的路由遷移過來
3、在router.js文件中橄浓,引入user模塊(通過require)