> For the complete documentation index, see [llms.txt](https://tofishes.gitbook.io/maty-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tofishes.gitbook.io/maty-js/api-fang-fa/ctx-kuo-zhan.md).

# ctx扩展

maty内部对ctx对象进行了一些方法和属性的扩展。使用maty时应避免覆盖扩展。

koa context原方法和属性参见[官方文档](https://koajs.com/#context)。

#### 扩展的属性

maty内部核心分为[request handler和response handler](/maty-js/master.md#gong-zuo-liu-cheng-shi-yi-tu)两个处理阶段，每个阶段都会产出扩展属性。

#### request handler产出的扩展属性

* ctx.isEnd\
  等于ctx.body !== undefined || ctx.status !== 404，表示可以去response了
* ctx.router\
  当前请求地址所匹配的路由配置对象
* ctx.interceptors\
  当前请求地址所匹配的拦截器配置对象集合
* ctx.reqBody\
  因为ctx.body用于响应内容，所以增加ctx.reqBody来获取post/put请求体参数。使用[koa-body](https://github.com/dlau/koa-body)模块来解析请求。
* ctx.request.files\
  上传的文件信息，参见[koa-body](https://github.com/dlau/koa-body)。
* ctx.param\
  路由中匹配的参数。例如 '/user/:name'， 则有 ctx.param.name。路由中匹配的所有参数同时会被合并到ctx.query和ctx.reqBody中。
* ctx.xhr\
  根据请求头'X-Requested-With'判断当前请求是否是ajax请求。
* ctx.ua\
  使用[ua-parser-js](https://github.com/faisalman/ua-parser-js)库解析user-agent请求头的结果。
* ctx.moduleName\
  获取请求路径的第一级名称。例如 /maty/hello，ctx.moduleName为maty。
* ctx.pathes\
  请求路径根据 '/' 分割的数组。例如 /maty/hello，ctx.pathes为\['maty', 'hello']。
* **ctx.httpRequestConfig**\
  此扩展属性比较特殊，需要在进入request handler前进行配置。\
  maty框架内部请求api接口使用的是request库，而httpRequestConfig是用来配置[request请求库的参数](https://github.com/request/request#requestoptions-callback)对象。用法示例见[Filter过滤器](/maty-js/pei-zhi/filter-guo-lv-qi.md#pei-zhi-request-ku-can-shu)。

#### response handler产出的扩展属性

* ctx.viewFile\
  视图模板对应的文件绝对路径。
* ctx.viewPath\
  视图模板对应的文件相对路径。
* ctx.viewExt\
  视图模板对应的文件后缀。
* ctx.apiInfo\
  记录api接口请求与响应所产生的信息
* ctx.apiData\
  记录api接口返回的数据。
* ctx.apisTask\
  记录api接口对应的请求任务。
* ctx.forwardUrl\
  调用ctx.forward()方法会产生该属性用于存储跳转的路径

#### 扩展的方法

* ctx.forward(url)\
  forward服务器内跳转，maty框架的核心功能之一。详见[有效利用Forward跳转](/maty-js/xiang-mu-shi-jian/forward-usage.md)。
* ctx.httpRequest()\
  获取用于请求api的apiRequest对象。apiRequest暂时只支持\['get', 'post', 'put', 'delete']方法。 例如：&#x20;

```javascript
const apiRequest = ctx.httpRequest();
apiRequest.get(options, callback);
```

* ctx.disableCache(disabled)\
  是否禁止本次response的缓存，当disabled为true时，添加如下响应头：\
  `'Cache-Control': 'no-cache, no-store, must-revalidate'`
