egg.js的基本使用和調(diào)用數(shù)據(jù)庫的方法示例
首先,整個項目的創(chuàng)建命令:
npm i egg-init -g //安裝egg egg-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中定義了我們的路由規(guī)則,所有的請求都會通過這個路由規(guī)則去找對應(yīng)的Controller,這樣也可以做到統(tǒng)一管控(如同前端初始化所有組件吧)。
接下來就是Controller控制層:
'use strict';
const Controller = require('egg').Controller;
class CustomController extends Controller {
async custonIndex() { //注意這里要定義成異步方法防止請求被阻塞
//let {id} = this.ctx.params; // 獲取路由參數(shù)
//let {name} = this.ctx.query; // 獲取用戶入?yún)?
let options = {id:'5', name:2}
let info = await this.ctx.service.customService.getInfo(options);//調(diào)用Service層傳參
處理,返回結(jié)果賦值
this.ctx.body = {
code: 200,
data: info
};//返回體
this.ctx.status = 200;
}
}
module.exports = CustomController;
發(fā)送請求會調(diào)用Controller中的方法,Controller中主要工作是接受用戶的參數(shù)并進行處理,然后將處理好的參數(shù)發(fā)送給Service層,然后把Service的結(jié)果返回給用戶。
其中對參數(shù)的處理包括但不僅限于參數(shù)校驗和參數(shù)拼裝,當(dāng)然也可以直接返回不走Service,都在Controller層做處理,但是不建議這樣做。
服務(wù)層(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層的數(shù)據(jù)之后,根據(jù)條件執(zhí)行對數(shù)據(jù)庫或者其他操作,最終將結(jié)果返回,一個請求的簡單流程就算是完成了
配置MySQL在egg-project\config\config.default.js里面,直接放上我的配置,具體起她的數(shù)據(jù)庫配置方法可以自查。
'use strict';
module.exports = appInfo => {
const config = exports = {
mysql:{
// 單數(shù)據(jù)庫信息配置
client: {
// host
host: '44.44.44.44',
// 端口號
port: '3306',
// 用戶名
user: 'mysq',
// 密碼
password: '359359',
// 數(shù)據(jù)庫名
database: 'mysql_db',
},
// 是否加載到 app 上,默認(rèn)開啟
app: true,
// 是否加載到 agent 上,默認(rèn)關(guān)閉
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和數(shù)據(jù)庫之間的基本操作了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
easyui combobox開啟搜索自動完成功能的實例代碼
下面小編就為大家?guī)硪黄猠asyui combobox開啟搜索自動完成功能的實例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11
ztree獲取當(dāng)前選中節(jié)點子節(jié)點id集合的方法
這篇文章主要介紹了ztree獲取當(dāng)前選中節(jié)點子節(jié)點id集合的方法,實例分析了ztree的方法transformToArray使用技巧,需要的朋友可以參考下2015-02-02
如何基于JS實現(xiàn)Ajax并發(fā)請求的控制詳解
通常為了減少頁面加載時間,先把核心內(nèi)容顯示處理,頁面加載完成后再發(fā)送ajax請求獲取其他數(shù)據(jù),這時就可能產(chǎn)生多個ajax請求,為了用戶體驗,最好是發(fā)送并行請求,這篇文章主要給大家介紹了關(guān)于如何基于JS實現(xiàn)Ajax并發(fā)請求控制的相關(guān)文章,需要的朋友可以參考下2021-08-08

