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;
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!