egg.js的基本使用和调用数据库的方法示例
首先,整个项目的创建命令:
npmiegg-init-g//安装egg egg-initegg-example--type=simple//初始化一个egg模板例子后面的type跟的是模板类型这里是简单的 cdegg-example//进入例子 npmi//安装依赖
可以去官方教程查看基本配置的讲解。
直接说使用,简单看过Egg的文档,官方文档对于入门还是很实用的,再配合一些别人的攻略很容易入门上手就可以使用。
首先router.js:
'usestrict';
/**
*@param{Egg.Application}app-eggapplication
*/
module.exports=app=>{
const{router,controller}=app;
router.get('/',controller.home.index);
router.get('/custom',controller.customController.custonIndex);//自定义controller的路由
};
router.js中定义了我们的路由规则,所有的请求都会通过这个路由规则去找对应的Controller,这样也可以做到统一管控(如同前端初始化所有组件吧)。
接下来就是Controller控制层:
'usestrict';
constController=require('egg').Controller;
classCustomControllerextendsController{
asynccustonIndex(){//注意这里要定义成异步方法防止请求被阻塞
//let{id}=this.ctx.params;//获取路由参数
//let{name}=this.ctx.query;//获取用户入参
letoptions={id:'5',name:2}
letinfo=awaitthis.ctx.service.customService.getInfo(options);//调用Service层传参
处理,返回结果赋值
this.ctx.body={
code:200,
data:info
};//返回体
this.ctx.status=200;
}
}
module.exports=CustomController;
发送请求会调用Controller中的方法,Controller中主要工作是接受用户的参数并进行处理,然后将处理好的参数发送给Service层,然后把Service的结果返回给用户。
其中对参数的处理包括但不仅限于参数校验和参数拼装,当然也可以直接返回不走Service,都在Controller层做处理,但是不建议这样做。
服务层(Service):
constService=require('egg').Service;
classCustimServiceextendsService{
asyncgetInfo(options){
constresults=awaitthis.app.mysql.select('test',{id:5});
returnresults[0].name;
}
}
module.exports=CustimService;
Service层拿到Controller层的数据之后,根据条件执行对数据库或者其他操作,最终将结果返回,一个请求的简单流程就算是完成了
配置MySQL在egg-project\config\config.default.js里面,直接放上我的配置,具体起她的数据库配置方法可以自查。
'usestrict';
module.exports=appInfo=>{
constconfig=exports={
mysql:{
//单数据库信息配置
client:{
//host
host:'44.44.44.44',
//端口号
port:'3306',
//用户名
user:'mysq',
//密码
password:'359359',
//数据库名
database:'mysql_db',
},
//是否加载到app上,默认开启
app:true,
//是否加载到agent上,默认关闭
agent:false,
}
};
//useforcookiesignkey,shouldchangetoyourownandkeepsecurity
config.keys=appInfo.name+'_17792_5967';
//addyourconfighere
config.middleware=[];
returnconfig;
};
这样,你就打通了egg和数据库之间的基本操作了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。