Controller控制器
https://eggjs.org/zh-cn/basics/controller.html
Controller功能
- 接收参数
 - 校验参数是否合法
 - 向下调用 Service服务,处理业务逻辑
 - ctx.body响应客户端数据
 
异步方法
Controller里面的方法都是异步的
/app/controller/home.js
'use strict';const { Controller } = require('egg');class HomeController extends Controller {async index() {const { ctx } = this;// ctx.body = 'hi, 启动项目成功';const res = await ctx.service.sku.index();// ctx.body = res;// 必须要加 await,否则路由 404await ctx.render('index.html', res);}}module.exports = HomeController;
获取config配置参数
Controller里面,要获取 config.default.js里面的配置,直接使用 this.config
| app | ctx | service | config | logger | helper | |
|---|---|---|---|---|---|---|
| Controller | this.app | this.ctx | this.service | this.config | this.logger | this.app.helper | 
| Service | 
Service里面调用远程API,await this.ctx.curl(url, {})
'use strict';const { Controller } = require('egg');class HomeController extends Controller {async index() {const { ctx } = this;const res = await ctx.service.sku.index();// const res = await ctx.curl(url, {})// ctx.body = res;// 必须要加 await,否则路由 404await ctx.render('index.html', res);}}module.exports = HomeController;
