koa的一些常用的middleware
Frameworks
Frameworks, boilerplates and other starter kits using Koa.
Middleware
Known middleware for Koa, you may want to search npm with “koa” to find more.
Security
Body Parsing
Parameter Validation
Rate Limiting
Vhost
Routing and Mounting
Documentation
File Serving
koa-static
静态文件服务中间件,是koa-send
的包装
安装
1 | npm install koa-static |
API
1 | API |
root
根目录 Stringopts
options object.
Options
maxage
浏览cache的最大时间ms 默认 0hidden
允不允许改变隐藏文件. 默认 falseindex
默认文件名, 默认 ‘index.html’defer
如果为true, 在return next()
之后, 服务器允许任何一个downstream middleware 首先回应.gzip
当用户支持gzip格式, 并且.gz这种文件存在就行. 默认 true.br
同上 .br 格式存在时 (但要注意这个只用在https中). 默认 true.setHeaders
Function to set custom headers on response.extensions
当在URL中没有匹配到扩展名时,那么会试着去从传过来的数组中匹配. 默认 false
Example
1 | const serve = require('koa-static'); |
SPDY
HTTP2
JSON and JSONP Responses
Compression
Caching
Authentication
Sessions
Templating
Services
CSS Preprocessor
Livereload
Error reporting
koa-onerror
就是一个抓错误的处理器 for koa, hack ctx.onerror.
就是handle all errors, steams’ and events’ errors
比koa-error使用简单,且抓的错误多
安装
1 | npm install koa-onerror |
使用
1 | const fs = require('fs'); |
Options
1 | onerror(app, options); |
- all: if options.all exist, ignore negotiation
- text: text error handler
- json: json error handler
- html: html error handler
- redirect: if accepct html, can redirect to another error page
check out default handler to write your own handler.
Status and Headers
koa-onerror
will automatic set err.status
as response status code, and err.headers
as response headers.
Logging
koa-logger
Development style logger middleware for koa.
注意: koa-logger@2
支持 koa@2
; 如果你想在 koa@1
中使用, 请使用 koa-logger@1
.
1 | <-- GET / |
安装
1 | npm install koa-logger |
使用
1 | const logger = require('koa-logger') |
Notes
Recommended that you .use()
this middleware near the top to “wrap” all subsequent middleware.
就是在顺序上放最上面来app.use(logger())
Metrics
Analytics
i18n or L10n
Response Transformation
Utilities
koa-convert
就是将只能在koa1中使用的middleware转换成koa2中能用的,当然也能反之咯.但注意有些不能转换 比如koa-router
安装
1 | npm install koa-convert |
使用
1 | const Koa = require('koa') // koa v2.x |
关于区分 legacy and modern middleware
就一个意思,通过 fn.constructor.name == 'GeneratorFunction'
来判断版本.
API
就3个,实现不管新版本还是旧版本都能使用middleware
一个将老的middleware转成新的,
一个混合老的和新的middleware都转成新的,
一个将新的middleware转成老的
- convert()
1 | modernMiddleware = convert(legacyMiddleware) |
- convert.compose()
1 | composedModernMiddleware = convert.compose(legacyMiddleware, modernMiddleware) |
- convert.back()
1 | legacyMiddleware = convert.back(modernMiddleware) |