安装mysql数据库插件
执行安装命令
cnpm/npm install egg-mysql --save
yarn add egg-mysql --save
在egg项目的config/plugin.js中添加
module.exports = {
mysql: {
enable: true,
package: 'egg-mysql'
}
}
在egg项目的config/config.default.js中添加
module.exports = {
config.mysql = {
client: {
host: 'localhost', // 自己的数据库host
port: '3306', // 自己的连接端口
user: 'root', // 可以使用root
password: 'root', // 数据库密码
database: 'database', // 要连接的数据库名称
},
app: true,
agent: false,
}
}
首先重新启动后台项目
在controller/articels
const Controller = require('egg').Controller
class ArticlesController extends Controller {
async articles() {
const { ctx } = this
var result = await ctx.service.articles.article()
console.log(result)
ctx.body = {
code: 1,
msg: 'success',
data: result
}
}
}
module.exports = ArticlesController
然后在 文件夹 app 里 新建 serveice 文件夹 在里面写 跟接口相同名称的js文件
// app/service/articles
const Service = require('egg').Service;
class ArticleService extends Service {
async article( ) {
const { app } = this
var result = app.mysqle.get('articles')
return result
});
module.exports = ArticeService