egg.js的基本使用和调用数据库的方法示例

Brenda ·
更新时间:2024-09-21
· 811 次阅读

首先,整个项目的创建命令:

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控制层:

'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的结果返回给用户。

其中对参数的处理包括但不仅限于参数校验和参数拼装,当然也可以直接返回不走Service,都在Controller层做处理,但是不建议这样做。

服务层(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层的数据之后,根据条件执行对数据库或者其他操作,最终将结果返回,一个请求的简单流程就算是完成了

配置MySQL在egg-project\config\config.default.js里面,直接放上我的配置,具体起她的数据库配置方法可以自查。

'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和数据库之间的基本操作了。



egg 调用 示例 方法 数据 js 数据库

需要 登录 后方可回复, 如果你还没有账号请 注册新账号