egg的resful风格
Method |
Path |
Route Name |
Controller.Action |
GET |
/posts |
posts |
app.controllers.posts.index |
GET |
/posts/new |
new_post |
app.controllers.posts.new |
GET |
/posts/:id |
post |
app.controllers.posts.show |
GET |
/posts/:id/edit |
edit_post |
app.controllers.posts.edit |
POST |
/posts |
posts |
app.controllers.posts.create |
PUT |
/posts/:id |
post |
app.controllers.posts.update |
DELETE |
/posts/:id |
post |
app.controllers.posts.destroy |
以vue + axios的技术基础做比较
业务层
<script>
import * as HomeAction from '@/api/home'
export default {
name: 'Home',
created () {
},
methods: {
fetchModel () {
HomeAction.fetchModel({ method: 'get' }).then(res => {
console.log(res)
}).catch(err => console.error(err))
},
update () {
HomeAction.update({ id: 15 }).then(res => {
console.log(res)
}).catch(err => console.error(err))
},
deleteModel () {
HomeAction.destroy(15).then(res => {
console.log(res)
}).catch(err => console.error(err))
},
fetchList () {
HomeAction.fetchList({ method: 'post' }).then(res => {
console.log(res)
}).catch(err => console.error(err))
}
}
}
</script>
API层
import fly from '@/utils/axios'
// 获取用户信息
export function fetchModel (params) {
return fly.get('/test/show', { params })
}
// 增加
export function fetchList (params) {
return fly.post('/test', params)
}
// 修改
export function update (params) {
return fly.put('/test/' + params.id, params)
}
// 删除
export function destroy (id) {
return fly.delete('/test/' + id)
}
以Egg + mongodb为后端技术架构为基础比较
业务层
'use strict';
const Controller = require('egg').Controller;
class TestController extends Controller {
constructor(ctx) {
super(ctx);
this.indexRule = {
page: { type: 'int?' },
page_size: { type: 'int?' },
};
}
async index() {
const { ctx } = this;
ctx.body = 'test resful 接口风格测试';
}
// 增加
async create() {
const { ctx } = this;
const res = ctx.request.body;
ctx.body = { status: 200, data: res, msg: '增加' };
}
// 改
async update() {
const { ctx } = this;
const res = ctx.params;
ctx.body = { status: 200, data: res, msg: '改' };
}
// 查
async show() {
const { ctx } = this;
const res = ctx.query;
ctx.body = { status: 200, data: res, msg: '查' };
}
// 删
async destroy() {
const { ctx } = this;
const res = ctx.params;
console.log(res, 2);
ctx.body = { status: 200, data: res, msg: '删' };
}
}
module.exports = TestController;
接口定义
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', '/api/', controller.home.index);
router.resources('test', '/api/test', controller.test);
router.resources('post', '/api/post', controller.post);
};