zoukankan      html  css  js  c++  java
  • egg.js 基础使用

    本文地址:https://www.cnblogs.com/veinyin/p/11944476.html

    controller service

    命名规则

    文件名小写

    class 名是 文件名大写 + Controller | Service  驼峰命名

    例: controller 文件夹下新建一个 user.js 文件

    class UserController extends Controller

     

    异步调用

     如果调用服务  需要用 async await 

    如果用 ejs 渲染页面  需要用 async await 

    调用方法

    this.app.controller.文件名.文件内定义的方法名

    this.service.文件名.文件内定义的方法名

    均可传参

    例 调用 controller 下 user 里的 info 方法  

    const res = await this.app.controller.user.info()

    路由传参

    route.js 中定义的路由 -> 地址栏输入的路由 

    取参方式 -> 取参结果

    get 传参

    url -> url?a=1

    this.ctx.query  -> { a: 1 }

    url/:id  -> url/1

    this.ctx.params -> { id: 1 }

    post 传参 

    this.ctx.request.body -> { a: 1, b: 2 }

    put 传参

    url/:id -> url/1

    this.ctx.params -> { id: 1 }

    delete 传参

    url/:id -> url/1

    this.ctx.params -> { id: 1 }

    post 请求配置 

    在 config/config.default.js 文件中添加

    const security = {
        csrf: {
            enable: false,
        },
    };

    静态资源

    放置目录 app/public   必须 /public 开头  避免路径问题

    例 使用图片资源

    app/public/images/demo.jpg

    <img src="/public/images/demo.jpg" />

     MySQL

    安装 egg-mysql 插件 参照文档配置 数据库相关信息

    egg 自动在 app 下挂载 mysql  可以通过 this.app.mysql 使用相关方法 

    get [表名, 查询条件]

    例:

    get('table_name', { id: 1 })  // 查询一条数据

     

    insert [表名, 插入内容]

    例: 

    insert('table_name', { a: 1, b: 2 })  // 插入数据

    select [表名, 可选项]

    where 查询条件 

    columns 要查询的项

    order 排序

    limit offset 翻页相关

    例:

    select('table_name')  // 查询表

    select('table_name', {

      where: { id: 1 },

      columns: ['name', 'age', 'gender'],

      order: [ ['id', 'desc'] ],

      limit: 10,

      offset: 0,

    });

     

    update [表名, 插入内容, 可选项]

    例:

    update('table_name', { name: 'yyh' }, { where: { userId: 1 } })

    默认用 ID 查询 如果插入内容内没设置就在 options 里面指定一下键名

    delete [表名, 删除条件]

    例: 

    delete('table_name', { id: 1 })

    query [语句] 

    例:

    query('select userName, userAge from table_name where id = ?', [1])

    如果要使用 sql 语句使用 query

     END~~~≥ω≤

  • 相关阅读:
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战01
    C语言寒假大作战02
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I博客作业10
    C语言I博客作业09
    C语言I博客作业08
    20199101 2019-2020-2 《网络攻防实践》综合实践
  • 原文地址:https://www.cnblogs.com/veinyin/p/11944476.html
Copyright © 2011-2022 走看看