关于eggjs:初始Egg框架

74次阅读

共计 5399 个字符,预计需要花费 14 分钟才能阅读完成。

前言

作为一名前端从业者不会点后端的常识怎么能够。node.js 成为了前端理解后端的首选。工欲善其事, 必先利其器本。一款好的框架。是提效的基本。这是一篇从 0 到 1 入门 egg 的文章。

三者区别与分割

Express 是基于 Node.js 平台,疾速、凋谢、极简的 Web 开发框架,老牌框架, 很多风行的框架的基石,简略且扩展性强,适宜做集体我的项目,本身短少束缚。
Koa 是基于 Node.js 平台的下一代 web 框架,由 Express 原班人马打造。特点: 玲珑灵便简略易用。作为企业级开发过于根底。
Egg 为企业级框架和利用而生,奉行约定优于配置。Egg 继承于 Koa
特点:

  • 提供基于 Egg [定制下层框架]的能力
  • 高度可扩大的[插件机制]
  • 内置[多过程治理]
  • 基于 [Koa]开发,性能优异
  • 框架稳固,测试覆盖率高
  • [渐进式开发]

    起步

    初始化我的项目:(脚手架)

    $ mkdir project-name// 创立一个空的文件夹
    $ npm init egg --type=simple//simple 示意骨架类型

    $ npm install || i // 装置依赖

    初始化我的项目后构造目录如图所示

    启动我的项目

    $ npm run dev// 开发环境中应用
    $ npm run start// 生产环境中应用

    文件目录介绍

    次要文件目录介绍

    |-app// 次要开发的文件
    | |-- controller// 解析用户的输出,解决后返回相应的后果
    | |-- db// 启动 mongodb 数据库的 dbpath 门路(可选)| |--extend// 框架的扩大(内置对象扩大)
    | | |---application.js//(固定名称)| | |---context.js//(固定名称)| | |---request.js//(固定名称)| | |---response.js//(固定名称)| | |---helper.js//(固定名称)| |--middleware// 编写中间件
    | |--model// 数据库中表的模型
    | |--publie// 动态资源
    | |--schedule// 定时工作
    | |--service// 编写业务逻辑层
    | |--view// 模板文件
    | |---router.js// 配置 URL 路由
    |-config// 寄存配置文件
    | |--config.default.js// 用于编写配置文件
    | |--plugin.js// 配置须要加载的插件
    |-test// 寄存单元测试
    |-logs// 日志文件
    |-package.json// 我的项目形容

    内置对象

    Application// 全局利用对象 =》继承于 koa
    Context// 申请级别对象 =》继承于 koa
    Request// 申请级别对象 =》继承于 koa
    Response// 申请级别对象 =》继承于 koa
    Controller// 基类
    Service// 基类
    Helper// 提供一些实用的 utility 函数, 本身是一个类
    Config// 配置
    Logger// 功能强大的日志性能
    Subscription// 基类定时工作

    路由(router)

    路由的作用:
    用来形容申请 URL 和具体承当执行动作的 Controller 的对应关系,用于对立所有路由规定。
    根本应用办法:
    在 app/router.js中定义 url 的规定

    'use strict';
    module.exports = app => {const { router, controller} = app;
    // 注册接口
    router.get('/logon', controller.logon.Logon);
    /**
    * 路由参数阐明
    *1.get 申请
    *2.url 为 /logon
    *3. 执行 controller 文件夹下的 logon 文件中的 Logon 办法
    **/
    };

    路由实战
    1. 参数获取
    如果是 get 申请

    ctx.query
    // 或
    ctx.params.xxx

    如果是 post 申请

    ctx.request.body

    2. 中间件应用

    /* 参数阐明:verb 示意申请形式例如 get、post
    path-match 示意路由 url 门路
    middleware1 示意应用 middleware1 中间件能够增加多个中间件
    app.controller.action 示意调用控制器中的办法
    */
    router.verb('path-match', middleware1, ..., middlewareN, app.controller.action);
    // 例子
    'use strict';
    module.exports = app => {const { router, controller} = app;
    // 获取中间件 record=>app.middlewarel.xxx 中 xxx 是 middleware 文件夹下对应的文件名
    const record=app.middlewarel.record();
    // 注册接口应用中间件
    router.get('/logon',record, controller.logon.Logon);
    };

    3. 多路由映射

    // app/router.js
    module.exports = app => {require('./router/news')(app);
    require('./router/admin')(app);
    };
    // app/router/news.js
    module.exports = app => {app.router.get('/news/list', app.controller.news.list);
    app.router.get('/news/detail', app.controller.news.detail);
    };
    // app/router/admin.js
    module.exports = app => {app.router.get('/admin/user', app.controller.admin.user);
    app.router.get('/admin/log', app.controller.admin.log);
    };

    控制器(controller)

    控制器的作用:
    负责解析用户的输出,解决后返回相应的后果
    根本应用办法:
    在 app/controller/logon.js

    'use strict';
    const Controller = require('egg').Controller;
    class LogonController extends Controller {async Logon() {const { ctx} = this;
    const req=ctx.query;
    const res=await ctx.service.logonService.logonUser(req);
    ctx.body = {
    code:200,
    msg:res
    }
    }
    }
    module.exports = LogonController;

    服务(service)

    服务的作用:
    简单业务场景下用于做业务逻辑封装的一个形象层
    根本应用办法:
    在 app/service/logonService.js

    'use strict'
    const Service=require('egg').Service;
    class logonService extends Service {async logonUser(obj){const {ctx}=this;
    console.log(obj)
    const res=await ctx.model.UserModel.find(obj);
    console.log(res)
    if(res.length!=0){return "该用户名已存在"}else{
    // 留神!!!!!! 内部文件援用 Model 模块中 ctx.model.xxx 中 xxx 指的是对应模块文件文件名并且文件名首字母必须是大写的(这个就有点哔了个狗了)const _User = new ctx.model.UserModel({
    UserName: obj.UserName,
    PassWord: obj.PassWord,
    });
    // mongoose 保留到数据库
    _User.save();
    return "注册胜利"
    }
    }
    }
    module.exports=logonService

    模块(model)

    模块的作用:
    定义数据表的内容
    根本应用办法:
    在 app/model/UserModel.js

    module.exports=app=>{const {mongoose}=app;
    const {Schema}=mongoose;
    const UserSchema=new Schema({UserName:{type:String},
    PassWord:{type:String}
    });
    return mongoose.model('UserModel',UserSchema,'users')
    }

    插件

    根本应用办法:
    在 config/plugin.js

    'use strict';
    module.exports = {
    mongoose:{
    enable:true,
    package:"egg-mongoose"
    },
    cors:{
    enable: true,
    package: 'egg-cors'
    }
    };

    在 confing/config.default.js

    'use strict';
    module.exports = appInfo => {
    /**
    * built-in config
    * @type {Egg.EggAppConfig}
    **/
    const config = exports = {};
    // use for cookie sign key, should change to your own and keep security
    config.keys = appInfo.name + '_1641975352438_173';
    // add your middleware config here
    config.middleware = [];
    // add your user config here
    const userConfig = {// myAppName: 'egg',};
    // 跨域
    config.security={
    csrf:{enable:false},
    domainWhiteList:['*']
    }
    config.cors={
    origin:"*",
    allowMethods:"GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
    }
    //mongoose 数据库配置
    config.mongoose={
    url:'mongodb://127.0.0.1:27021/VietNamVisa',
    options:{useNewUrlParser:true,useUnifiedTopology:true},// 其余配置
    }
    return {
    ...config,
    ...userConfig,
    };
    };

    定时工作

    根本应用办法:
    在 app/schedule

    const Subscription = require('egg').Subscription;
    class RemoveFile extends Subscription {
    // 通过 schedule 属性来设置定时工作的执行距离等配置
    static get schedule() {
    return {
    interval: '1m', // 每 1 分钟
    type: 'all', /* 参数有 all 和 worker*/
    };
    }
    // subscribe 是真正定时工作执行时被运行的函数
    async subscribe() {// 执行的办法}
    }
    module.exports =GetTime;

    简写

    module.exports = {
    schedule: {
    cron: '0 0 */3 * * *',// 示意 3 小时执行
    type: 'all', // 指定所有的 worker 都须要执行
    },
    async task(ctx) {
    const res = await ctx.curl('http://www.api.com/cache', {dataType: 'json',});
    ctx.app.cache = res.data;
    },
    };

    框架扩大

    根本应用办法:
    在 app/extend/application.js

    module.exports ={
    // 办法扩大
    methodName(){const methodF=time()
    return methodF
    }
    // 属性扩大
    get attributeName(){return "我是扩大属性"}
    function time(){办法内容。。。。}
    }

    应用 application 扩大的办法和属性

    const {app}=this
    // 调用 application 扩大的办法
    app.methodName()
    /// 调用 application 扩大的属性
    app.attributeName

    根本应用办法:
    在 app/extend/context.js

    // 扩大办法和属性同 application 雷同

    应用 application 扩大的办法和属性

    const {ctx}=this
    // 调用 application 扩大的办法
    ctx.methodName()
    /// 调用 application 扩大的属性
    ctx.attributeName

    根本应用办法:
    在 app/extend/request.js

    // 同上

    拜访办法:

    ctx.request.xxx

    根本应用办法:
    在 app/extend/response.js

    // 同上

    拜访办法:

    ctx.response.xxx

    根本应用办法:
    在 app/extend/helper.js

    // 同上

    拜访办法:

    ctx.helper.xxx

    以上就是 egg 基础知识的分享。

正文完
 0