跟着官网安装就好了,官网很详细,可以是用快速初始化,也可以跟着官网一步一步搭出框架,新手我建议还是逐步搭建比较好,可以了解框架结构,对框架理解回跟深入
输出hello word
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
}
module.exports = HomeController;
访问文件,具体文件操作可以看这两个文章,node-file案例,node-file文件处理方法
'use strict';
const { Controller } = require('egg');
const fsp = require('fs').promises;
class TestController extends Controller {
async index() {
const { ctx, config } = this;
const fileContent = await fsp.readFile(config.static.dir + '/test.xlsx', 'utf8');
const editContent = await fsp.writeFile(config.static.dir + '/test.xlsx', 'test1');
ctx.body = fileContent;
}
}
module.exports = TestController;
调用外部接口
'use strict';
const { Controller } = require('egg');
const fsp = require('fs').promises;
class TestController extends Controller {
async index() {
const { ctx, config } = this;
// 这里我用的在线mock工具,随便找一个在线mock工具就行
const result = await ctx.curl('https://mock.presstime.cn/mock/6520f61af82aa50021bbdc40/example/test', {
dataType: 'json',
});
const res = result.data.data.records.reduce((pre, item) => {
return (pre += `${item.qualificationName}`);
}, '');
ctx.body = res;
}
}
module.exports = TestController;
连接mysql需要用到插件 egg-mysql,参考官网-教程-MySQL
注意:
开启插件需要放在 plugn.js 中,这块官网写的确实不是很细,给初学者很不友好,这里我刚开始按照官网直接配置有问题,数据库就连不上。
module.exports = {
mysql: {
enable: true,
package: 'egg-mysql',
}
};
配置数据源也不能按照官网的来,和上面一样,我卡了挺久,查了好久资料。配置完这两步,就可以开始crud了。
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {
mysql: {
client: {
// host
host: '',
// 端口号
port: '',
// 用户名
user: '',
// 密码
password: '',
// 数据库名
database: '',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
}
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_123456';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
使用 server 层中连接数据库,返回数据,controller 中做逻辑处理。按照官网的步骤做就好了。