egg.js是一个node.js后台web框架,类似express,koa优点:规范,插件机制Egg.js约定了一套代码目录结构(配置config,路由router,extendedextend,middlewaremiddleware,controller)标准化的目录结构可以让不同团队的开发者使用该框架编写的代码风格更加一致,接管成本也会更低。目录app/router.js用于配置URL路由规则app/contorller/**用于解析用户输入,处理后返回相应结果app/service/**用于编写业务逻辑层[可选]app/middleware/**用于编写中间件[可选]app/service/**用于框架扩展[可选]...自定义目录app/view/**用于防止模板文件[可选]加载顺序Egg指的是应用程序,框架和插件作为负载单元(loadUnit);在加载过程中,Egg会遍历所有的加载单元,加载时有一点优先级。插件=>框架=>应用程序按顺序加载。首先加载依赖方。框架按继承顺序加载,层数越低越早。如果这样的应用配置如下Dependsonapp|├──plugin2(依赖plugin3)|└──plugin3└──framework1|└──plugin1└──egg最后的加载顺序是=>plugin1=>plugin3=>plugin2=>egg=>framework1=>app文件加载顺序package.json=>config=>app/extend=>app.js=>app/service=>app/middleware=>app/controller=>app/router.jsrouter首先我们需要配置路由,因为我们在实际开发中,会用到很多路由,所以这里我们将路由改成home.js//app/router/home.js'usestrict'moduleexports=app=>{const{home}=app.controller//Gethome.分层并在app下创建一个router文件夹存放路由文件home.js//app/router/home.js控制器下的jsapp.get('/',home.index);app.get('/home/param',home.getParam);app.get('/home/postParam',home.postParam);}//app/router.js'usestrict'constRouteHome=require('./router/home');module.exports={const{router,controller}=app;RouteHome(app);}//app/controller/home.js'usestrict'constController=require('egg').Controller;classHomeControllerextendsController{asyncindex(){awaitthis.ctx.render('/索引',{name:'蛋'});}asyncgetParam(){letid=awaitthis.ctx.query.id;this.ctx.body=id;}asyncpostParam(){让id=awaitthis.ctx。请求.body.id;//获取post参数this.ctx.body=id;}}moduleexports=HomeController;controller我们根据方法和URL将用户的请求通过Router分发到对应的Controller,Controller负责解析用户的Input,处理后返回对应的结果。框架建议Controller层主要处理(校验和转换)用户的请求参数,然后调用相应的服务方法处理业务。获取业务结果后,封装返回所有Controller文件,必须放在app/controller目录下,当可以支持多级目录访问时,可以通过目录名进行级联访问//在app中新建controller/controller目录'usestrict'constController=required('egg').Controller;classCustomerControllerextendsController{asynccustomIndex(){//ctx.body是ctx.response.body的简写,不要与ctx.request.body混淆this.ctx.body='thisismycontroller';}}module.exports=CustomController;//在router.js中配置路由(访问时请求的路径)'usestrict'module.exports=app=>{//相当于获取app文件夹下的router和controllerconst{路由器,控制器}=应用程序;router.get('/',controller.home.index);router.get('/custom',controller.customerController.customIndex);}定义了Controller类,每次请求访问服务器时都会实例化一个全新的对象,项目中的Controller类继承自egg.Controller,而下面的属性会挂在this上——this.ctx框架封装了处理当前请求的各种方便的属性和方法——this。app框架提供的全局对象和方法-this.service访问抽象业务层相当于this.ctx.service-this.config运行配置项-this.logger日志服务业务逻辑层'usestrict';constService=require('egg').Service;classcustomServiceextendsService{asyncshow(zc,hh){//异步反阻塞returnzc+"and"+hh;}}module.exports=UserService;//控制器代码'usestrict';constController=require('egg').Controller;classCustomControllerextendsController{asynccustonIndex(){letstr=awaitthis.ctx.service.customService.show('zc','hh');//使用await获取异步方法的返回值this.ctx.body='thisismycontroller'+str;}}module.exports=CustomController;一个更完整的例子//app/router.jsmodule.exports=app=>{app.router.get('/user/:id',app.controller.user.info);};//app/controller/user.jsconstController=require('egg').Controller;classUserControllerextendsController{asyncinfo(){constuserId=ctx.params.id;constuserInfo=awaitctx.service.user.find(userId);ctx.body=用户信息;}}module.exports=UserController;//app/service/user.jsconstService=require('egg').Service;classUserServiceextendsService{//默认不需要提供构造函数//constructor(ctx){//super(ctx);如果需要在构造函数中做一些处理,就必须有这句话来保证`thislaterUseof.ctx`。////可以直接通过this.ctx获取ctx////也可以直接通过this.app获取app//}asyncfind(uid){//如果我们获取用户id,从中获取用户详情数据库信息constuser=awaitthis.ctx.db.query('select*fromuserwhereuid=?',uid);//假设这里有一些复杂的计算,然后返回需要的信息。constpicture=awaitthis.getPicture(uid);返回{名称:user.user_name,年龄:user.age,图片,};}asyncgetPicture(uid){constresult=awaitthis.ctx.curl(`http:///photoserver/uid=${uid}`,{dataType:'json'});返回结果.data;}}module.exports=UserService;//curlhttp://127.0.0.1:7001/user/1234helperapp工具类存放在/extend文件夹下//app/extend/getName.js'usestrict'模块。exports={getUserName(id){returnlist.find(i=>i.id===id).name;}}//app/extend/helper.js'usestrict'constgetName=require('./getName');module.exports={showName(){returngetName.getUserName('2221');}}//controller引用helper'usestrict'constController=require('egg').Controller;classCustomControllerextendsController{asynccustomIndex(){////this.ctx.helper获取内置对象helper并进入helper.js文件this.ctx.body=this.ctx.helper.showName();}}module.exports=CustomController;页表面染egg.js使用的是nunjucks页面模板//在config/plugin.js里面添加'usestrict'exports.nunjucks={enable:true,package:'egg-view-nunjucks'}//config/config/default.js添加'usestrict'...module.exports=app=>{...config.view={mapping:{'.html':'nunjucks'},root:path.join(appInfo.baseDir,'app/view')}...returnconfig;}//app/routes/sign.js'usestrict';module.exports=(router,controller)=>{router.get('/sign/modifyPassword',controller.sign.modifyPassword);};//app/controller/sign.js'使用严格';constController=require('egg').Controller;类SignController扩展控制器{asyncmodifyPassword(){const{ctx}=this;//冲洗view/sign/modifyPassword.htmlawaitctx.render('sign/modifyPassword.html');}}module.exports=SignController;
