Egg.js 控制器基类 BaseController、控制器兼容写法

在app/core/base.js

复制代码
'use strict';


const Controller = require('egg').Controller;

class BaseController extends Controller {
  async getUserInfo() {

    return{

        name:'张三',
        age:20
    }
  }

  async success(redirectUrl){
    await this.ctx.render('public/success',{

        redirectUrl:redirectUrl||'/'
    });

  }
  async error(redirectUrl){
        await this.ctx.render('public/error',{

            redirectUrl:redirectUrl||'/'
        });

  }
  notFound(msg) {
    msg = msg || 'not found';
    this.ctx.throw(404, msg); }
}

module.exports = BaseController;
复制代码

继承基类:

复制代码
'use strict';


const BaseController = require('../core/base.js');

class UserController extends BaseController {
  async login() {
        await this.ctx.render('login');
  }
  async register() {
         await this.ctx.render('register');
  }

  async doLogin() {
      
       console.log(this.ctx.request.body);
    
      //注意 await

      await this.success('/login');

  }
  async doRegister() {
      console.log(this.ctx.request.body);

      await this.error('/register');
     
  }
}

module.exports = UserController;
复制代码

 

posted on   LoaderMan  阅读(582)  评论(0编辑  收藏  举报

编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!
· 【译】Visual Studio(v17.13)中新的调试和分析特性
历史上的今天:
2017-06-16 防微信左滑删除的效果
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示