1.初始化项目
快速生成项目:
$ npm i egg-init -g
$ egg-init egg-example --type=simple
$ cd egg-example
$ npm i
启动项目:
$ npm run dev
$ open localhost:7001
2.安装启动数据库
npm i --save egg-mysql
开启插件:
开启插件:
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
3.配置数据库
config.mysql = {
// 单数据库信息配置
client: {
// host
host: 'api',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: 'root',
// 数据库名
database: 'cms',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
//关闭csrf
config.security={
csrf:false
}
4。编写路由
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.resources('user', '/user', controller.user);
};
5.编写控制器
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
async create() {
const { ctx } = this;
ctx.body = 'hi, create';
}
async update() {
const { ctx } = this;
ctx.body = 'hi, update';
}
async destroy() {
const { ctx } = this;
ctx.body = 'hi, destroy';
}
}
module.exports = UserController;