国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

egg.js的基本使用和調用數據庫的方法示例

2024-05-06 15:39:17
字體:
來源:轉載
供稿:網友

首先,整個項目的創建命令:

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;};            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: SHOW| 永修县| 文水县| 武清区| 阳信县| 泌阳县| 泰和县| 资源县| 柳林县| 葵青区| 资溪县| 鱼台县| 广汉市| 尖扎县| 天津市| 体育| 台山市| 宁化县| 滦南县| 恭城| 开原市| 福海县| 瓦房店市| 怀远县| 綦江县| 深泽县| 乡宁县| 沭阳县| 呼伦贝尔市| 东丰县| 乌海市| 乌拉特中旗| 深水埗区| 石河子市| 宜阳县| 合阳县| 汽车| 孝义市| 图木舒克市| 昭平县| 通州区|