Step-1
官方代码:examples/progressive/step1 at master · eggjs/examples · GitHub
主要是记录一下自己踩的坑,
一开始写的代码是这样的:
app/controller/home.js
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = ctx.isIOS()
//this.ctx.body = `isIOS: ${this.ctx.isIOS}`;
}
}
module.exports = HomeController;
然后一直报
500
TypeError in /
ctx.isIOS is not a function
这个错误,和官方的代码比对了一下,isIOS是get方法,相当于把isIOS定义成了属性,所以不要加括号
正确写法:
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = ctx.isIOS
//this.ctx.body = `isIOS: ${this.ctx.isIOS}`;
}
}
module.exports = HomeController;
此外,const { ctx } = this 这个写法:
相当于从this中获取ctx
const { ctx } = this
//等于
this.ctx
所以这几行代码是等价的:
const { ctx } = this
ctx.body = ctx.isIOS
this.ctx.body = `isIOS: ${this.ctx.isIOS}`;