1 安装,推荐直接使用脚手架,只需几条简单指令,即可快速生成项目
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple //init是将生成的文件夹名称
$ npm i
1.1 启动项目-测试:
$ npm run dev
$ open http://localhost:7001
2 Router 主要用来描述请求 URL 和具体承担执行动作的 Controller 的对应关系, 框架约定了 app/router.js 文件用于统一所有路由规则。
router.js
router.get('/product',controller.product.index);
对应的controller/product.js
'use strict';
const Controller = require('egg').Controller;
class ProductController extends Controller {
async index() {
const {
ctx
} = this;
ctx.body = 'product';
}
}
module.exports = ProductController;
2.2 get请求2种传参方式
1 http://127.0.0.1:7001/product/detail?id=123
ctx.query获取
2 http://127.0.0.1:7001/product/detail2/1234
ctx.params获取
2.3 post请求本地调试会出现安全威胁csrf的防范
config.default.js内可临时设置关闭安全插件
config.security = {
csrf: false
};
2.4 post请求相关
- ctx.request.body获取post的参数
- 使用JSON传数据
3 Service 服务 抽象出来的 Service 可以被多个 Controller 重复调用,Service服务可调用其它Service,Controller不可调用其它Controller。
3.1 app创建service文件夹,文件夹再创建各个service服务,如下面的product.js
'use strict';
const Service = require('egg').Service;
class ProductService extends Service {
async index() {
return {
id: 100,
name: '测试'
}
}
}
module.exports = ProductService;
3.2在controller的接口使用service
const res = await ctx.service.product.index();
4 静态资源都存放在public文件夹下,可新建img,css,js等文件夹
4.1 模板引擎引入静态资源文件直接使用public/css/main.css直接引入
5 连接数据库mysql
5.1 安装 cnpm i --save egg-mysql
5.2 开启插件
// config/plugin.js
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
5.3 单数据源 - config.default.js中配置
config.mysql = {
// 单数据库信息配置
client: {
// host
host: 'localhost',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: '123456',
// 数据库名
database: 'egg_article',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
5.4 controller或service中获取数据
const res = await app.mysql.select(‘article’);
console.log(res);
5.5 Create直接使用 insert 方法插入一条记录。
// 插入
const result = await this.app.mysql.insert('posts', { title: 'Hello World' });
// 在 post 表中,插入 title 为 Hello World 的记录
5.6 Read直接使用 get 方法或 select 方法获取一条或多条记录。select 方法支持条件查询与结果的定制。
//查询一条记录
const post = await this.app.mysql.get('posts', { id: 12 });
//=> SELECT * FROM `posts` WHERE `id` = 12 LIMIT 0, 1;
//查询全表
const results = await this.app.mysql.select('posts');
//=> SELECT * FROM `posts`;
//条件查询和结果定制
const results = await this.app.mysql.select('posts', { // 搜索 post 表
where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE 条件
columns: ['author', 'title'], // 要查询的表字段
orders: [['created_at','desc'], ['id','desc']], // 排序方式
limit: 10, // 返回数据量
offset: 0, // 数据偏移量
});
//=> SELECT `author`, `title` FROM `posts`
// WHERE `status` = 'draft' AND `author` IN('author1','author2')
// ORDER BY `created_at` DESC, `id` DESC LIMIT 0, 10;
5.7 Update直接使用 update 方法更新数据库记录。
// 修改数据,将会根据主键 ID 查找,并更新
const row = {
id: 123,
name: 'fengmk2',
otherField: 'other field value', // any other fields u want to update
modifiedAt: this.app.mysql.literals.now, // `now()` on db server
};
const result = await this.app.mysql.update('posts', row); // 更新 posts 表中的记录
// => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE id = 123 ;
5.8 Delete可以直接使用 delete 方法删除数据库记录。
const result = await this.app.mysql.delete('posts', {
author: 'fengmk2',
});
// => DELETE FROM `posts` WHERE `author` = 'fengmk2';
6.0 moment.js插件-自动创建当前日期与时间
6.1安装
cnpm i --save moment
6.2应用
//引入
const moment = require('moment');
//设置参数
const params = {
...ctx.request.body,
createTime: moment().format('YYYY-MM-DD HH:mm:ss') //format设置存储格式
};