【Cxinny】Egg

  • 搭建开发环境
    yarn create egg --type=simple 进行默认配置
    yarn install  安装依赖包
    yarn dev  启动egg
  •  Egg VS Express/Koa
  • 项目结构介绍

    app:代码开发目录,有controller文件夹:控制性目录,public文件夹,router.js:项目的路由文件
    config:config.default.js:项目配置目录;plugin.js插件目录
    logs:项目的日志文件
    node_modules:依赖包
    run:临时文件
    test:测试文件
    typings:TS文件
    jsconfig.json:js配置文件
  • 新建访问

  • controller控制器
    做的事情:(1)RESTful  增删改查数据库,返回数据;(2)HTML 根据不同的URL返回渲染内容的不同;(3)代理服务器  中间件,向别的服务器请求再拿到相应结果
  • 编写controller
    // myController.js
    const Controller = require('egg').Controller;
    class myController extends Controller{
        async index(){
            const { ctx } = this;
            ctx.body = '<h1>hhh</h1>'
        }
    }
    module.exports = myController
    
    // router.js
    router.get('/my',Controller.myController.index)
     
  •  单元测试编写
    'use strict'
    const { app } = require('egg-mock/bootstrap');
    
    describe('myController -index',()=>{
        it('myController index page',()=>{
            return app.httpRequest()
                .get('/myController')
                .expect(200)  //期待收到状态码200
                .expect("<h1>hhh</h1>")  //期待收到页面
        })
    })
    测试:yarn test 注意测试的时候不要开启dev
  • 异步测试
    // myController.js
    async getBoys(){
        const { ctx } = this;
        await new Promise(()=>{
            setTimeout(()=>{
                resolve(ctx.body = '<h1>getBoys</h1>')
            },5000)
        })
    }
    
    // router.js
    router.get('/getBoys',controller.myController.getBoys)
    
    // myController.test.js
    it('myController getBoys page',()=>{
        return app.httpRequest()
            .get('/getBoys')
            .expect(200)  //期待收到状态码200
            .expect("<h1>getBoys</h1>")  //期待收到页面
    })
  •  Get请求和参数传递
    // myController.js  自由传参模式
    getBoy(){
        const { ctx } = this;
        ctx.body = ctx.query
    }
    
    // router.js
    router.get('/getBoy',controller.myController.getBoy)
    
    // url:/getBoy?name="hhh"&age="18"
    
    // myController.js 严格传参模式
    getBoy2(){
        const { ctx } = this;
        ctx.body = ctx.query.name
    }
    
    // router.js
    router.get('/getBoy2/:name',controller.myController.getBoy2)
    
    // url:/getBoy?name="hhh"  必须有name,不然404

  • post请求和参数接受
    // myController.js  自由传参模式
    getBoy3(){
        const { ctx } = this;
        ctx.body = {
            status:200,
            data:ctx.request.body
        }
    }
    
    // router.js
    router.post('/getBoy3',controller.myController.getBoy3)
    
    // url:/getBoy3
    
    // myController.js 严格传参模式
    getBoy2(){
        const { ctx } = this;
        ctx.body = ctx.query.name
    }
    
    // router.js
    router.get('/getBoy2/:name',controller.myController.getBoy2)
    
    // url:/getBoy?name="hhh"  必须有name,不然404

  •  Service 封装的一个抽象层,数据库交互的代码
    保持Controller 逻辑更加简单
    独立性,Service 多个Controller
    写测试用例简单
  • Service的编写和使用方法
    在app文件夹下新建service文件夹,再新建myService.js
    'use strict';
    const Service = require("egg").Service;
    class myService extends Service{
        async getBoy(id){
            return{
                id:id,
                name:"hhh",
                age:18,
            }
        }
    }
    
    //controller调用,所以service都是异步
    async getBoy(){
        const ctx = this.ctx
        const res = await ctx.service.myService.getBoy("66")
        ctx.body = res
    }

     
  •  View中使用EJS模板引擎
    使用服务端渲染好处:对SEO非常友好
    安装:npm i egg-view-ejs --save  或yarn add egg-view-ejs
    配置plugin.js
    'use strict';
    
    exports.ejs = {
        enable:true,
        package:"egg-view-ejs"
    }
    配置config.default.js
    config.view = {
        mapping:{
            ".html":"ejs"
        }
    }
    config.ejs = {
        delimiter:"$"  //把%换成$
    }
    使用模板引擎
    async index(){
        const { ctx } = this;
        await ctx.render("hh.html",{
            id:2021,
            name:"hh",
            age:18,
            skill:"play",
            language:["yuwen","yingyu","riyu"],
        })
    }
    //在app文件夹下新建view文件夹,在view里新建hh.html
    body写
    <h1>你好,我是<%=name%>,<%=age%>岁,专业技能是<%=skill%></h1>
    <% for(var i=0;i<skills.length;i++>){ %>
    <li><%=skills[i] %><li>
    <%}%>
    启动项目访问路由
    // 新建css文件夹,default.css
    
    // 引用,跟原生的一样
    <link ref="stylesheet" type="text/css" href="public/css/default.css" />
  • cookie的增删改查
    httpOnly=true 只允许在服务端操作
  • egg.js中间件的编写和使用
    // app文件夹新建middleware 新建counter.js
    
    module.exports = options =>{
        return async (ctx,next)=>{
            if(ctx.session.counter){
                ctx.session.counter++
            }else{
                ctx.session.counter=1
            }
            await next();
        }
    }
    
    // config.default.js  这里是全局中间件
    config.middleware = ['counter']
    
    // router.js  指定路由中间件
    const counter = app.middleware.counter()
    router.get('/index',counter,controller.home.index);
  • egg.js的扩展
  • egg.js的Extend-application
    // app文件夹新建extend,新建application.js
    module.exports = {
        // 方法扩展
        currentTime(){
            return getTime();
        }
    }
    function getTime(){
        let now = new Date();
        return now;
    }
  • egg.js的Extend-context
     
    // app文件夹新建extend,新建context.js
    module.exports = {
        params(key){
            const methods = this.request.method;
            if(method === 'GET'){
                return key ? this.query[key]:this.query;
            }else{
                return key ?this.request.body[key]:this.request.body;
            }
        }
    }
    
    // 使用
    const params = ctx.params();
  •  egg.js的Extend-request
    // app新建extend,新建request.js
    module.exports = {
        get token(){
            return this.get("token")
        }
    }
    
  •   egg.js的Extend-response
    // app新建extend,新建response.js
    module.exports = {
        get token(){
            return this.get("token")
        }
    }
  •  egg.js的Extend-helper
    // app新建extend,新建helper.js
    module.exports = {
        base64Encode(str=''){
            return new Buffer(str).toString('base64');
        }
    }
    // 使用
    const testBase64 = ctx.helper.base64Encode('hhhh')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值