egg初体验

egg初体验

一、框架介绍、安装

1. egg的个人理解

  • koa官网,官网中国呢的文档还是挺详细的
  • 之前接触过nodejs的话很容易上手,只是框架不同写法上有区别而已。
  • egg就是一个框架,做了一些封装,从 koa 发展过来,写法上都大同小异,个人使用过感觉 egg 写起来更加方便。

2. 安装

跟着官网安装就好了,官网很详细,可以是用快速初始化,也可以跟着官网一步一步搭出框架,新手我建议还是逐步搭建比较好,可以了解框架结构,对框架理解回跟深入

  • egg快速入门
  • 官网逐步搭建的时候,你可能会不知道应该在那个地方创建文件,在那个地方创建文件夹,这个时候看一下完整的的目录结构就全清楚了。

二、controller

  • 输出hello word

    js 复制代码
    'use strict';
    
    const { Controller } = require('egg');
    
    class HomeController extends Controller {
      async index() {
        const { ctx } = this;
        ctx.body = 'hi, egg';
      }
    }
    
    module.exports = HomeController;
  • 访问文件,具体文件操作可以看这两个文章,node-file案例,node-file文件处理方法

    js 复制代码
    'use strict';
    
    const { Controller } = require('egg');
    const fsp = require('fs').promises;
    
    class TestController extends Controller {
      async index() {
        const { ctx, config } = this;
    
        const fileContent = await fsp.readFile(config.static.dir + '/test.xlsx', 'utf8');
    
        const editContent = await fsp.writeFile(config.static.dir + '/test.xlsx', 'test1');
    
        ctx.body = fileContent;
      }
    }
    
    module.exports = TestController;
  • 调用外部接口

    js 复制代码
      'use strict';
    
      const { Controller } = require('egg');
      const fsp = require('fs').promises;
    
      class TestController extends Controller {
        async index() {
          const { ctx, config } = this;
          // 这里我用的在线mock工具,随便找一个在线mock工具就行
          const result = await ctx.curl('https://mock.presstime.cn/mock/6520f61af82aa50021bbdc40/example/test', {
            dataType: 'json',
          });
    
          const res = result.data.data.records.reduce((pre, item) => {
            return (pre += `<div>${item.qualificationName}</div>`);
          }, '');
    
          ctx.body = res;
        }
      }
    
      module.exports = TestController;

数据库

  • 连接mysql需要用到插件 egg-mysql,参考官网-教程-MySQL

  • 注意:

    • 开启插件需要放在 plugn.js 中,这块官网写的确实不是很细,给初学者很不友好,这里我刚开始按照官网直接配置有问题,数据库就连不上。

      js 复制代码
        module.exports = {
          mysql: {
            enable: true,
            package: 'egg-mysql',
          }
        };
    • 配置数据源也不能按照官网的来,和上面一样,我卡了挺久,查了好久资料。配置完这两步,就可以开始crud了。

      js 复制代码
        module.exports = appInfo => {
          /**
           * built-in config
           * @type {Egg.EggAppConfig}
           **/
          const config = exports = {
            mysql: {
              client: {
                // host
                host: '',
                // 端口号
                port: '',
                // 用户名
                user: '',
                // 密码
                password: '',
                // 数据库名
                database: '',
              },
              // 是否加载到 app 上,默认开启
              app: true,
              // 是否加载到 agent 上,默认关闭
              agent: false,
            }
          };
      
          // use for cookie sign key, should change to your own and keep security
          config.keys = appInfo.name + '_123456';
      
          // add your middleware config here
          config.middleware = [];
      
          // add your user config here
          const userConfig = {
            // myAppName: 'egg',
          };
      
      
          return {
            ...config,
            ...userConfig,
          };
        };
  • 使用 server 层中连接数据库,返回数据,controller 中做逻辑处理。按照官网的步骤做就好了。

相关推荐
李游Leo18 小时前
Node.js 多版本管理与 nvm/nvs 使用全流程(含国内镜像加速与常见坑)
node.js
Q_Q196328847519 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
陈随易1 天前
适合中国宝宝的AI编程神器,文心快码
前端·后端·node.js
Q_Q19632884751 天前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php
EndingCoder1 天前
Electron 新特性:2025 版本更新解读
前端·javascript·缓存·electron·前端框架·node.js·桌面端
machinecat1 天前
node,小程序合成音频的方式
前端·node.js
草木红1 天前
express 框架基础和 EJS 模板
arcgis·node.js·express
亮子AI2 天前
【npm】npm 包更新工具 npm-check-updates (ncu)
前端·npm·node.js
Yvonne爱编码2 天前
构建高效协作的桥梁:前后端衔接实践与接口文档规范详解
前端·git·ajax·webpack·node.js
Juchecar2 天前
AI教你常识之 ESM + Express + Vue3 + CSV文件 + Pinia + CRUD
node.js