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 中做逻辑处理。按照官网的步骤做就好了。

相关推荐
hoLzwEge7 小时前
pnpm vs npm:新一代包管理器的范式革命
前端框架·node.js
麻辣凉茶7 小时前
给阿嬤一封来自云端的信(上)
前端·node.js
codingWhat1 天前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
见过夏天3 天前
Node.js 常用命令全攻略
node.js
前端双越老师3 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen4 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding4 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt5 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好6 天前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊8 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js