node_egg内置基础对象

egg框架内置基础对象

1.Application对象

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
  }
}

2.Context对象

context是一个请求级别的对象,每次收到用户请求时,框架会实例化一个context对象
context对象封装了用户请求的信息,并提供了许多方法来获取请求参数或者设置响应信息
框架会将所有的service挂载到Context实例上,一些插件也会将一些方法挂载到它上面(egg-squelize)
// 访问方式
在 Service 中获取和 Controller 中获取的方式一样,可以通过 this.ctx 访问到Context对象
middleware(中间件) 中 this 就是 ctx,例如 this.cookies.get('foo')。
helper中的 this 指向 helper对象本身,使用 this.ctx 访问 context 对象,例如 this.ctx.cookies.get('foo')。

3.Request && Response 对象

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); 
  }
}

4.Controller

框架提供了一个 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
    };
  };

5.Service

框架提供了一个 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
  };
};
posted @   前端之旅  阅读(560)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示