Koa
Koa 是一个非常轻量易用 的 Web 框架。本章节内容,主要介绍在 Midway 中如何使用 Koa 作为上层框架,并使用自身的能力。
Midway 默认的示例都是基于该包。
@midwayjs/koa 包默认使用 koa@2 以及集成了 @koa/router 作为路由基础能力,并默认内置了 session 和 body-parser 功能。
| 描述 | |
|---|---|
| 包含独立主框架 | ✅ |
| 包含独立日志 | ✅ |
安装依赖
$ npm i @midwayjs/koa@3 --save
或者在 package.json 中增加如下依赖后,重新安装。
{
"dependencies": {
"@midwayjs/koa": "^3.0.0",
// ...
},
}
也可以直接使用脚手架创建示例。
# npm v6
$ npm init midway --type=koa-v3 my_project
# npm v7
$ npm init midway -- --type=koa-v3 my_project
开启组件
import { Configuration, App } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import { join } from 'path';
@Configuration({
imports: [koa],
importConfigs: [join(__dirname, './config')],
})
export class MainConfiguration {
@App()
app: koa.Application;
async onReady() {
// ...
}
}
BodyParser
@midwayjs/koa 自带 bodyParser 功能,默认会解析 Post 请求,自动识别 json 和 form 类型。
如需 text 或者 xml,可以自行配置。
默认的大小限制为 1mb,可以单独对每项配置大小。
// src/config/config.default
export default {
// ...
bodyParser: {
enableTypes: ['json', 'form', 'text', 'xml'],
formLimit: '1mb',
jsonLimit: '1mb',
textLimit: '1mb',
xmlLimit: '1mb',
},
}
注意,使用 Postman 做 Post 请求时的类型选择:

关闭 bodyParser 中间件。
// src/config/config.default
export default {
// ...
bodyParser: {
enable: false,
// ...
},
}
Cookie 和 Session
@midwayjs/koa 默认封装了 cookies 解析和 Session 的支持,可以查看 Cookies 和 Session。