Egg.js
基于Node.js和Koa企业级应用开发框架
特性
提供基于Egg的定制上层框架的能力
高度可扩展的插件机制
内置多进程管理
基于Koa开发性能优异
框架稳定,测试覆盖率搞
渐进式开发
涉及内容
vant ui
vue-cli3
moment.js
Egg.js
mysql
前后端联调
开发环境
Egg.js
https://eggjs.org/zh-cn/intro/quickstart.html
$ node -v v10.16.0 $ mkdir egg-demo && cd egg-demo $ npm init egg --type=simple $ cnpm i $ npm run dev
路由
app/router.js
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); };
GET传参
1、方式一
/product/detail?id=110
// 路由 router.get('/product/detail', controller.product.detail); // 控制器 async detail() { const { ctx } = this; console.log(ctx.query); // { id: '110' } ctx.body = `id=${ctx.query.id}`; }
2、方式二
/product/detail2/110
// 路由 router.get('/product/detail2/:id', controller.product.detail2); // 控制器 async detail2() { const { ctx } = this; console.log(ctx.params); // { id: '110' } ctx.body = `id=${ctx.params.id}`; }
POST请求
// 配置文件关闭csrf config.security = { csrf: { enable: false, }, }; // 路由 router.post('/product/create', controller.product.create); // 控制器 async create() { const { ctx } = this; console.log(ctx.request.body); // { name: 'Tom' } const {name, age} = ctx.request.body; ctx.body = {name, age}; }
POST请求 /product/create
Content-Type application/x-www-form-urlencoded Content-Type application/json name: "Tom"
返回
{ "name": "Tom" }
PUT请求
/product/update/110
// 路由 router.put('/product/update/:id', controller.product.update); // 控制器 async update() { const { ctx } = this; console.log(ctx.params); // { id: '110' } ctx.body = {id: ctx.params.id}; }
DELETE请求
/product/delete/110
// 路由 router.delete('/product/delete/:id', controller.product.delete); // 控制器 async delete() { const { ctx } = this; console.log(ctx.params); // { id: '110' } ctx.body = { id: ctx.params.id }; }
Service
app/service/product.js
'use strict'; const Service = require('egg').Service; class productService extends Service { async index() { return { name: "Tom", age: 18 }; } } module.exports = productService;
// 路由 router.get('/product', controller.product.index); // 修改控制器使用service async index() { const { ctx } = this; const res = await ctx.service.product.index(); ctx.body = res; }
访问后返回: /product/
{ "name": "Tom", "age": 18 }