内置对象
Request & Response
可以在 Context 的实例上获取到当前请求的 Request( ctx.request
) 和 Response( ctx.response
) 实例。
-
ctx.response.body=
和ctx.body=
是等价的。 - [!] 需要注意的是,获取 POST 的 body 应该使用
ctx.request.body
,而不是ctx.body
Controller
框架提供了一个 Controller 基类,并推荐所有的 Controller 都继承于该基类实现。这个 Controller 基类有下列属性:
- ctx - 当前请求的 Context 实例。
-
app
- 应用的 Application 实例。 -
config
- 应用的 配置 。 -
service
- 应用所有的 service 。 -
logger
- 为当前 controller 封装的 logger 对象。
Service
框架提供了一个 Service 基类,并推荐所有的 Service 都继承于该基类实现。 Service 基类的属性和 Controller 基类属性一致,访问方式也类似
中间件
编写中间件
一个中间件是一个放置在 app/middleware
目录下的单独文件,它需要 exports 一个普通的 function,接受两个参数:
- options: 中间件的配置项,框架会将
app.config[${middlewareName}]
传递进来。 - app: 当前应用 Application 的实例。
// app/middleware/error_handler.js
module.exports = () => {
return async function errorHandler(ctx,next) {
try {
await next();
} catch (err) {
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
ctx.app.emit('error',err,ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error = status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
// 从 error 对象上读出各个属性,设置到响应中
if (status === 422) {
ctx.body = {
code: ctx.ERROR_CODE,data: error,msg: '参数错误'+status
};
}
500) {
ctx.body = {
code: 500,data: '',0);">'服务端错误-----'+error
};
}
ctx.status = 200;
}
};
};复制代码
使用
在应用中使用中间件
在应用中,我们可以完全通过配置来加载自定义的中间件,并决定它们的顺序。
如果我们需要加载上面的 gzip 中间件,在 config.default.js
中加入下面的配置就完成了中间件的开启和配置: