內(nèi)置對象
Request & Response
可以在 Context 的實例上獲取到當前請求的 Request( ctx.request ) 和 Response( ctx.response ) 實例。
ctx.response.body= 和 ctx.body= 是等價的。
[!] 需要注意的是,獲取 POST 的 body 應該使用 ctx.request.body ,而不是 ctx.body
Controller
框架提供了一個 Controller 基類,并推薦所有的 Controller 都繼承于該基類實現(xiàn)。這個 Controller 基類有下列屬性:
ctx - 當前請求的 Context 實例。
app - 應用的 Application 實例。
config - 應用的 配置 。
service - 應用所有的 service 。
logger - 為當前 controller 封裝的 logger 對象。
Service
框架提供了一個 Service 基類,并推薦所有的 Service 都繼承于該基類實現(xiàn)。 Service 基類的屬性和 Controller 基類屬性一致,訪問方式也類似
中間件
編寫中間件
一個中間件是一個放置在 app/middleware 目錄下的單獨文件,它需要 exports 一個普通的 function,接受兩個參數(shù):
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 上觸發(fā)一個 error 事件,框架會記錄一條錯誤日志
ctx.app.emit('error', err, ctx);
const status = err.status || 500;
// 生產(chǎn)環(huán)境時 500 錯誤的詳細錯誤內(nèi)容不返回給客戶端,因為可能包含敏感信息
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: '參數(shù)錯誤'+status
};
}
if (status === 500) {
ctx.body = {
code: 500,
data: '',
msg: '服務端錯誤-----'+error
};
}
ctx.status = 200;
}
};
};復制代碼
使用
在應用中使用中間件
在應用中,我們可以完全通過配置來加載自定義的中間件,并決定它們的順序。
如果我們需要加載上面的 gzip 中間件,在 config.default.js 中加入下面的配置就完成了中間件的開啟和配置:
// 加載 errorHandler 中間件
config.middleware = ['errorHandler']復制代碼
電話咨詢
在線咨詢
QQ咨詢
官方微信
TOP