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 2020-06-16 21:40  LoaderMan  阅读(581)  评论(0编辑  收藏  举报

导航