本文介绍Egg.js框架的基本使用流程,涵盖项目初始化、路由配置、Controller与Service层的职责划分,以及如何在config.default.js中配置MySQL数据库连接,帮助开发者快速搭建后端服务。
Egg.js项目初始化与路由配置
首先,执行项目创建命令:
npm i egg-init -g //安装egg
egg-init egg-example --type=simple //初始化一个egg模板例子 后面的type跟的是模板类型这里是简单的
cd egg-example//进入例子
npm i //安装依赖
具体基本配置可参考官方教程。
直接上手使用,简要阅读Egg文档后,发现官方文档对入门者十分友好,结合其他教程即可快速上手。
首先是router.js文件:
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/custom',controller.customController.custonIndex); //自定义controller的路由
};
router.js用于定义路由规则,所有请求均通过此规则映射到对应的Controller,实现统一管控(类似于前端初始化所有组件)。
接下来是Controller控制层:
Controller与Service层协作机制
'use strict';
const Controller = require('egg').Controller;
class CustomController extends Controller {
async custonIndex() { //注意这里要定义成异步方法防止请求被阻塞
//let {id} = this.ctx.params; // 获取路由参数
//let {name} = this.ctx.query; // 获取用户入参
let options = {id:'5', name:2}
let info = await this.ctx.service.customService.getInfo(options);//调用Service层传参
处理,返回结果赋值
this.ctx.body = {
code: 200,
data: info
};//返回体
this.ctx.status = 200;
}
}
module.exports = CustomController;
请求发送后会调用Controller中的方法,Controller主要负责接收用户参数并进行处理,随后将处理后的参数传递给Service层,最后将Service层返回的结果反馈给用户。
参数处理包括但不仅限于参数校验和参数拼装,也可以直接在Controller层返回结果而不经过Service,但这种方式不推荐。
服务层(Service):
const Service = require('egg').Service;
class CustimService extends Service {
async getInfo(options) {
const results = await this.app.mysql.select('test',{id:5});
return results[0].name;
}
}
module.exports = CustimService;
Service层接收Controller层的数据后,根据条件执行数据库或其他操作,最终将结果返回,这样一个简单的请求流程即告完成。
在egg-project\config\config.default.js中配置MySQL,直接参考我的配置示例,其他数据库配置方法可自行查阅。
MySQL数据库配置方法
'use strict';
module.exports = appInfo => {
const config = exports = {
mysql:{
// 单数据库信息配置
client: {
// host
host: '44.44.44.44',
// 端口号
port: '3306',
// 用户名
user: 'mysq',
// 密码
password: '359359',
// 数据库名
database: 'mysql_db',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
}
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_17792_5967';
// add your config here
config.middleware = [];
return config;
};
至此,你已打通Egg与数据库之间的基本操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。