Application是全局应用对象,在一个应用中,只会实例化一个,可以在它上面挂载一些全局的方法和对象
在继承于Controller, Service 基类的实例中,可以通过 this.app 访问到Application对象。
// app/controller/user.js
class UserController extends Controller {
async fetch() {
this.app.username = ‘zhangsan‘
this.ctx.body = this.ctx.service.user.echo();
}
};
// app/service/user.js
class UserService extends Service {
async echo() {
return ‘hello‘+ this.app.username
}
}
context是一个请求级别的对象,每次收到用户请求时,框架会实例化一个context对象
context对象封装了用户请求的信息,并提供了许多方法来获取请求参数或者设置响应信息
框架会将所有的service挂载到Context实例上,一些插件也会将一些方法挂载到它上面(egg-squelize)
在 Service 中获取和 Controller 中获取的方式一样,可以通过 this.ctx 访问到Context对象
Request 封装了node原生的HTTPRequest对象,提供一些辅助方法获取HTTP请求常用参数
Response 封装了node原生的HTTPResponse对象,提供一些辅助方法设置HTTP响应
可以在 Context 的实例上获取到当前请求的 Request(ctx.request) 和 Response(ctx.response) 实例。
// app/controller/user.js
class UserController extends Controller {
async fetch() {
//query是get请求获取参数的方法
const id = this.ctx.request.query.id;
// this.ctx.reseponse.body 是this.ctx.body的全写
this.ctx.response.body = tihs.ctx.service.user.echo(id);
}
}
框架提供了一个 Controller 基类,并推荐所有的 Controller 都继承于该基类实现
定义Controller类,会在每一个请求访问到server时实例化一个全新的对象,
项目中Controller类继承于egg.Controller,会有几个属性挂载this上
· this.ctx: 当前请求的上下文Context对象的实例,处理当前请求的各种属性和方法
· this.app: 当前应用Application对象的实例,获取框架提供的全局对象和方法
· this.service: 应用定义的Service,可以访问到抽象出的业务层,等价于this.ctx.service
· this.config: 应用运行时的配置项
· this.logger: logger对象,对象上有四个方法(debug, info, warn, error)分别代表打印不同级别的日志
在 Controller 文件中,可以通过两种方式来引用 Controller 基类:
// app/controller/user.js
// 从 egg 上获取(推荐)
const Controller = require(‘egg‘).Controller;
class UserController extends Controller {
// implement
}
module.exports = UserController;
// 从 app 实例上获取
module.exports = app => {
return class UserController extends app.Controller {
// implement
};
};
框架提供了一个 Service 基类,并推荐所有的 Service 都继承于该基类实现。
Service 基类的属性和 Controller 基类属性一致,访问方式也类似:
// app/service/user.js
// 从 egg 上获取(推荐)
const Service = require(‘egg‘).Service;
class UserService extends Service {
// implement
}
module.exports = UserService;
// 从 app 实例上获取
module.exports = app => {
return class UserService extends app.Service {
// implement
};
};
原文:https://www.cnblogs.com/JunLan/p/12574515.html