常用中间件
Koa 中间件 | 功能 |
---|---|
@koa/router | 官方中间件,借鉴了 koa-router 用于处理路由的中间件,用法类似 express.Router |
koa-bodyparser | 解析请求体的中间件,支持 x-www-form-urlencoded、application/json 格式的请求体 |
koa-views | 渲染模板引擎的中间件,一般用于传统的服务端渲染 |
koa-static | 用于搭建静态资源服务器的中间件 |
koa-static-cache | 实现了 http 缓存的静态资源中间件 |
koa-session | session 中间件 |
koa-jwt | 支持 jwt 的中间件 |
koa-compress | 支持 gzip 动态压缩的中间件 |
koa-logger | 日志记录中间件 |
@koa/cors | 官方中间件,支持 CORS 跨域的中间件 |
@koa/multer | 官方中间件,借鉴了 koa-multer 用户处理文件上传的中间件 |
koa-connect | 将 express 或 connect 中间件转换为 koa 中间件 |
http-proxy-middleware | 代理中间件 |
connect-history-api-fallback | 单页应用支持 |
koa-convert | 用于将旧版本的 koa 中间件转换为 koa2 中间件 |
使用示例
koa-compose
可以将多个中间件合成为一个
const Koa = require('koa')
const fs = require('fs')
const util = require('util')
const compose = require('koa-compose')
const app = new Koa()
const a1 = (ctx, next) => {
console.log('a1')
next()
}
const a2 = (ctx, next) => {
console.log('a2')
next()
}
const a3 = (ctx, next) => {
console.log('a3')
next()
}
app.use(compose([a1, a2, a3]))
app.listen(3000, () => { console.log('http://localhost:3000') })
koa-static
提供静态资源托管
const Koa = require('koa')
const static = require('koa-static')
const path = require('path')
const mount=require('koa-mount') // 支持请求前缀
const app = new Koa();
app.use(mount('/app',static(path.join(__dirname, '../dist/'))))
app.use(static('./public'))
app.use(static(path.join(__dirname, './public')))
app.listen(3000, () => { console.log('http://localhost:3000') })
koa-mount
给静态资源设置虚拟路径
const Koa = require('koa')
const static = require('koa-static')
const path = require('path')
const mount = require('koa-mount')
const app = new Koa()
app.use(mount('/foo', static(path.join(__dirname, './public')))
app.listen(3000, () => { console.log('http://localhost:3000') })
koa-router
Express 路由风格(app.get、app.put、app.post …)
const Koa = require('koa');
const Router = require('@koa/router');
const app = new Koa();
const router = new Router();
router.get('/', (ctx, next) => {
// ctx.router available
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000, () => { console.log('http://localhost:3000') })
打赏作者
您的打赏是我前进的动力
微信
支付宝
Koa👉 API 使用
上一篇
评论