在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;