1. 起步
纯讲理论知识大家可能会觉得很枯燥乏味,所以我个人习惯采用代码结合理论的形式为大家阐述 Egg
的一些关键知识点。
Egg 的环境要求:Node >= 8.x,npm >= 6.1.0。
通过nvm安装node (node版本管理工具)
① 卸载系统上现有node(如果有)
此处基于windows下nvm安装node之后npm命令找不到问题解决办法,在此基础上简化和完善。
在卸载程序中卸载node
在环境变量中删除所有与node相关的路径(无论是user级,还是system级)
删除以下路径的文件(可能只有部分文件才有) C:\Program Files (x86)\nodejs
C:\Program Files\nodejs
C:\Users{User}\AppData\Roaming\npm
C:\Users{User}\AppData\Roaming\npm-cache
C:\Users{User}\node_modules (在我电脑上的路径)
②下载最新版nvm并安装nvm-setup.zip
③更换镜像源
在路径 C:\Users\{User}\AppData\Roaming\nvm\settings.txt下添加以下两条
node_mirror: https://npm.taobao.org/mirrors/node/
npm_mirror: https://npm.taobao.org/mirrors/npm/
此时如果你还仔细观察,会发现C:\Program Files下的nodejs问的其实是一个快捷方式,指向的是nvm的安装路径C:\Users\{user}\AppData\Roaming\nvm下对应的node版本。
④ 执行命令
$ nvm install 14.16.1
⑤安装yarn
$ npm i -g yarn
这里我们使用 Egg
为我们提供的脚手架生成指令,几行代码就能初始化一个 Egg
项目,如下:
$ mkdir egg
$ cd egg
$ npm init egg --type=simple
$ yarn 或者 npm i
注意: 这里不用npm的原因是npm install 会出现一些奇奇怪怪的问题,一路按回车就可以了。
我们来看一下egg项目的目录,和 Java 的MVC架构差不多,controller是控制层、service是业务层。
app
controller
home.js
router.js
config
config.default.js
plugin.js
router.js
上面代码是监听路径/
,访问/
后会调用controller.home.index
的方法,如下
ctx.body
就是返回的JSON
对象,我们启动代码看看
$ yarn run dev
访问localhost:7001
2. 连接mysql
数据库
先创建test
表练练手先,表字段如图所示,varchar类型长度一般取适合即可,我这里为了方便全部取100。
$ yarn add egg-mysql
在config/plugin.js
添加插件配置:
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
mysql: {
enable: true,
package: 'egg-mysql'
}
};
在 config/config.default.js
,添加 mysql
连接配置项和 安全威胁 csrf 的防范
:
config.mysql = {
// 单数据库信息配置
client: {
// host
host: 'localhost',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: '数据库密码', // 初始化密码,没设置的可以不写
// 数据库名
database: 'juejue-cost', // 我们新建的数据库名称
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
config.security = {
csrf: {
enable: false,
ignoreJSON: true
},
domainWhiteList: [ '*' ], // 配置白名单
};
- 查询用户(注意添加顺序,先service层后controller层,最后添加路由,否则会找不到对应的路径报错)
// 在service/home.js添加
async user() {
const { ctx, app } = this;
let sql = `select id,name from test`;
try {
const result = await app.mysql.query(sql);
return result;
} catch (e) {
console.log(e);
return null;
}
}
// 在controller/home.js添加
async user() {
const { ctx } = this;
const result = await ctx.service.home.user();
ctx.body = result;
}
// 在router.js
router.get('/user', controller.home.user);
- 增加用户
async addUser(name) {
const { ctx, app } = this;
try {
const result = await app.mysql.insert('test', { name });
return result;
} catch (e) {
console.log(e);
return null;
}
}
async addUser() {
const { ctx } = this;
const { name } = ctx.request.body;
try {
const result = await ctx.service.home.addUser(name);
ctx.body = {
code: 200,
msg: '添加成功',
data: null
}
} catch (error) {
ctx.body = {
code: 500,
msg: '添加失败',
data: null
}
}
}
router.post('/add-user', controller.home.addUser);
- 修改用户
async editUser(id, name) {
const { ctx, app } = this;
try {
let result = await app.mysql.update('test', { name }, {
where: {
id
}
});
return result;
} catch (error) {
console.log(error);
return null;
}
}
async editUser() {
const { ctx } = this;
const { id, name } = ctx.request.body;
try {
const result = await ctx.service.home.editUser(id, name);
ctx.body = {
code: 200,
msg: '修改成功',
data: null
}
} catch (error) {
ctx.body = {
code: 500,
msg: '修改失败',
data: null
}
}
}
router.post('/edit-user', controller.home.editUser);
- 删除用户
async deleteUser(id) {
const { ctx, app } = this;
try {
let result = await app.mysql.delete('test', { id });
return result;
} catch (error) {
console.log(error);
return null;
}
}
async deleteUser() {
const { ctx } = this;
const { id } = ctx.request.body;
try {
const result = await ctx.service.home.deleteUser(id);
ctx.body = {
code: 200,
msg: '删除成功',
data: null
}
} catch (error) {
ctx.body = {
code: 500,
msg: '删除失败',
data: null
}
}
}
router.post('/delete-user', controller.home.deleteUser);
3. 正式写项目代码
- 创建数据库
这里只需要记得id都是自增的就行了,这里贴出来type表的数据,仅供参考。
-- ----------------------------
-- Table structure for type
-- ----------------------------
DROP TABLE IF EXISTS `type`;
CREATE TABLE `type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`type` varchar(255) NOT NULL COMMENT '1:支出;2:收入',
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of type
-- ----------------------------
BEGIN;
INSERT INTO `type` VALUES (1, '餐饮', '1', 0);
INSERT INTO `type` VALUES (2, '服饰', '1', 0);
INSERT INTO `type` VALUES (3, '交通', '1', 0);
INSERT INTO `type` VALUES (4, '日用', '1', 0);
INSERT INTO `type` VALUES (5, '购物', '1', 0);
INSERT INTO `type` VALUES (6, '学习', '1', 0);
INSERT INTO `type` VALUES (7, '医疗', '1', 0);
INSERT INTO `type` VALUES (8, '旅行', '1', 0);
INSERT INTO `type` VALUES (9, '人情', '1', 0);
INSERT INTO `type` VALUES (10, '其他', '1', 0);
INSERT INTO `type` VALUES (11, '工资', '2', 0);
INSERT INTO `type` VALUES (12, '奖金', '2', 0);
INSERT INTO `type` VALUES (13, '转账', '2', 0);
INSERT INTO `type` VALUES (14, '理财', '2', 0);
INSERT INTO `type` VALUES (15, '退款', '2', 0);
INSERT INTO `type` VALUES (16, '其他', '2', 0);
INSERT INTO `type` VALUES (17, '测试', '1', 5);
COMMIT;
这里先使用我部署好的线上API接口,等我有空了我再补充Egg后端的代码上来。
【点击进入API接口文档】(记得在浏览器下载一个JSON格式化工具打开,否则会很乱)