首先,整個項目的創建命令:
npm i egg-init -g //安裝eggegg-init egg-example --type=simple //初始化一個egg模板例子 后面的type跟的是模板類型這里是簡單的cd egg-example//進入例子npm i //安裝依賴
可以去官方教程查看基本配置的講解。
直接說使用,簡單看過Egg的文檔,官方文檔對于入門還是很實用的,再配合一些別人的攻略很容易入門上手就可以使用。
首先router.js:
'use strict';/** * @param {Egg.Application} app - egg application */module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); router.get('/custom',controller.customController.custonIndex); //自定義controller的路由};
router.js中定義了我們的路由規則,所有的請求都會通過這個路由規則去找對應的Controller,這樣也可以做到統一管控(如同前端初始化所有組件吧)。
接下來就是Controller控制層:
'use strict';const Controller = require('egg').Controller;class CustomController extends Controller { async custonIndex() { //注意這里要定義成異步方法防止請求被阻塞 //let {id} = this.ctx.params; // 獲取路由參數 //let {name} = this.ctx.query; // 獲取用戶入參 let options = {id:'5', name:2} let info = await this.ctx.service.customService.getInfo(options);//調用Service層傳參 處理,返回結果賦值 this.ctx.body = { code: 200, data: info };//返回體 this.ctx.status = 200; }}module.exports = CustomController;
發送請求會調用Controller中的方法,Controller中主要工作是接受用戶的參數并進行處理,然后將處理好的參數發送給Service層,然后把Service的結果返回給用戶。
其中對參數的處理包括但不僅限于參數校驗和參數拼裝,當然也可以直接返回不走Service,都在Controller層做處理,但是不建議這樣做。
服務層(Service):
const Service = require('egg').Service;class CustimService extends Service { async getInfo(options) { const results = await this.app.mysql.select('test',{id:5}); return results[0].name; }}module.exports = CustimService;
Service層拿到Controller層的數據之后,根據條件執行對數據庫或者其他操作,最終將結果返回,一個請求的簡單流程就算是完成了
配置MySQL在egg-project/config/config.default.js里面,直接放上我的配置,具體起她的數據庫配置方法可以自查。
'use strict';module.exports = appInfo => { const config = exports = { mysql:{ // 單數據庫信息配置 client: { // host host: '44.44.44.44', // 端口號 port: '3306', // 用戶名 user: 'mysq', // 密碼 password: '359359', // 數據庫名 database: 'mysql_db', }, // 是否加載到 app 上,默認開啟 app: true, // 是否加載到 agent 上,默認關閉 agent: false, } }; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_17792_5967'; // add your config here config.middleware = []; return config;};
這樣,你就打通了egg和數據庫之間的基本操作了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答