最近在接手一个项目,vue+nuxt+egg,我也是刚开始学习egg.js,所以会将自己踩的坑都记录下来。
安装mysql
使用sequelize连接数据库,首先安装egg-sequelize和mysql2。
npm install --save egg-sequelize mysql2
打开package.json文件,查看安装是否成功和对应的版本。
{"name": "enmo-admin-server","version": "1.0.0","description": "","private": true,"egg": {"declarations": true},"dependencies": {"await-stream-ready": "^1.0.1","egg": "^2.15.1","egg-scripts": "^2.11.0","egg-sequelize": "^5.2.1","egg-swagger-doc": "^2.2.9","egg-validate": "^2.0.2","egg-view-assets": "^1.6.1","egg-view-ejs": "^2.0.1","lodash": "^4.17.11","moment": "^2.24.0","ms": "^2.1.1","mysql2": "^2.1.0","sha1": "^1.1.1"},"devDependencies": {"autod": "^3.0.1","autod-egg": "^1.1.0","egg-bin": "^4.11.0","egg-ci": "^1.11.0","egg-mock": "^3.21.0","eslint": "^5.13.0","eslint-config-egg": "^7.1.0","sequelize-cli": "^6.1.0"},"engines": {"node": ">=10.0.0"},"scripts": {"start": "egg-scripts start --daemon --title=egg-server-enmo-admin-server","stop": "egg-scripts stop --title=egg-server-enmo-admin-server","dev": "egg-bin dev","debug": "egg-bin debug","test": "npm run lint -- --fix && npm run test-local","test-local": "egg-bin test","cov": "egg-bin cov","lint": "eslint .","ci": "npm run lint && npm run cov","autod": "autod"},"ci": {"version": "10"},"repository": {"type": "git","url": ""},"author": "","license": "MIT"
}
在config/plugin.js中启用eggsequelize插件
// config/plugin.js
exports.sequelize = {enable: true,package: 'egg-sequelize',
};
在config/config.default.js中添加sequelize配置
// config/config.default.js
config.sequelize = {dialect: 'mysql',host: '127.0.0.1',port: 3306,database: 'egg-sequelize-doc-default',username: 'root',password: 'w123456',
}
在数据库中创建表并插入数据
在app/model/user.js中编写代码实现业务逻辑
// app/model/user.js
'use strict';module.exports = app => {const {STRING,INTEGER,} = app.Sequelize;const User = app.model.define('user', {id: {type: INTEGER,primaryKey: true,autoIncrement: true,},name: STRING(50),sex: STRING(4),pass: STRING(32),}, {freezeTableName: true,timestamps: false,});return User;
};
这个Model就可以在Controller和Service中通过app.model.User访问,编写Controller调用这个Model
// app/controller/user.js
'use strict';const Controller = require('egg').Controller;class UserController extends Controller {async index() {const _ctx = this.ctx;const user = await _ctx.model.User.findAll();_ctx.body = user;}
}module.exports = UserController;
将controller挂载到路由上
// app/router.js
module.exports = app => {const { router, controller } = app;router.resources('users', '/users', controller.users);
};
使用npm run dev命令启动项目。在localhost:7001/user看到数据库中的数据。