💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] 随着ES6的普及,async/await的语法受到更多JS开发者的青睐,Koa.js作为比较早支持使用该语法的Node框架越来越受到大家的喜爱,虽然Koa.js本身支持的功能很有限,但官方和社区提供了很多各种功能的中间件,精选了我们开发应用程序或者框架将会特别有用的中间件。 Koa.js 插件可以到[https://github.com/koajs/koa/wiki](https://github.com/koajs/koa/wiki)获取。 # [koa-router](https://github.com/ZijianHe/koa-router) 路由是Web框架必不可少的基础功能,koa.js为了保持自身的精简,并没有像Express.js自带了路由功能,因此koa-router做了很好的补充,作为koa星数最多的中间件,koa-router提供了全面的路由功能,比如类似Express的app.get/post/put的写法,URL命名参数、路由命名、支持加载多个中间件、嵌套路由等。 Basic usage: ~~~js var Koa = require('koa'); var Router = require('koa-router'); var app = new Koa(); var router = new Router(); router.get('/', (ctx, next) => { // ctx.router available }); app .use(router.routes()) .use(router.allowedMethods()); ~~~ # [koa-bodyparser](https://github.com/koajs/bodyparser) koa.js并没有内置Request Body的解析器,当我们需要解析请求体时需要加载额外的中间件,官方提供的koa-bodyparser是个很不错的选择,支持x-www-form-urlencoded, application/json等格式的请求体,但不支持form-data的请求体。 ## Usage ~~~js var Koa = require('koa'); var bodyParser = require('koa-bodyparser'); var app = new Koa(); app.use(bodyParser()); app.use(async ctx => { // the parsed body will store in ctx.request.body // if nothing was parsed, body will be an empty object {} ctx.body = ctx.request.body; }); ~~~ # [koa-multer](https://github.com/koa-modules/multer) ~~~jvascripta const Koa = require('koa') const multer = require('koa-multer') const Router = require('koa-router') const app = new Koa(); const router = new Router(); const upload = multer({ dest: 'uploads/' }); //路由 router.post('/upload', upload.single('file'), async (ctx, next) => { ctx.body = { filename: ctx.req.file.filename//返回文件名 } }) app.use(router.routes()).use(router.allowedMethods()) app.listen(3000); ~~~ 也可以配置storage ```javascript //文件上传 //配置 const storage = multer.diskStorage({ //文件保存路径 destination: function (req, file, cb) { cb(null, 'public/uploads/') }, //修改文件名称 filename: function (req, file, cb) { var fileFormat = (file.originalname).split("."); //以点分割成数组,数组的最后一项就是后缀名 cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]); } }) //加载配置 const upload = multer({ storage: storage }); ``` # [koa-views](https://github.com/queckezz/koa-views) koa-views对需要进行视图模板渲染的应用是个不可缺少的中间件,支持ejs, nunjucks等众多模板引擎。 ## Example ~~~js const Koa = require('koa') const Router = require('koa-router') const views = require('koa-views') const compose = require('koa-compose') const path = require('path') const app = new Koa() // Must be used before any router is used app.use(views(path.join(__dirname, 'views'), { map: { html: 'nunjucks' } //需要安装nunjucks包 })) const router = new Router() router.get('/', async (ctx, next) => { await ctx.render('multer', { title: 'Hello koa2' }) }) //组合多个中间件,中间件执行区分顺序 const all = compose([router.routes(), router.allowedMethods()]); app.use(all); app.listen(3000, () => { console.log('server is running at http://localhost:3000') }); ~~~ # [koa-static](https://github.com/koajs/static) Node.js除了处理动态请求,也可以用作类似Nginx的静态文件服务,在本地开发时特别方便,可用于加载前端文件或后端Fake数据。 ~~~js const Koa = require('koa'); const app = new Koa(); app.use(require('koa-static')(root, opts)); ~~~ * `root`root directory string. nothing above this root directory can be served * `opts`options object. ## Example ~~~js const serve = require('koa-static'); const Koa = require('koa'); const app = new Koa(); // $ GET /package.json app.use(serve('.')); // $ GET /hello.txt app.use(serve('test/fixtures')); // or use absolute paths app.use(serve(__dirname + '/test/fixtures')); app.listen(3000); console.log('listening on port 3000'); ~~~ # [koa-session](https://github.com/koajs/session) HTTP是无状态协议,为了保持用户状态,我们一般使用Session会话,koa-session提供了这样的功能,既支持将会话信息存储在本地Cookie,也支持存储在如Redis, MongoDB这样的外部存储设备。 ## Example View counter example: ~~~js const session = require('koa-session'); const Koa = require('koa'); const app = new Koa(); app.keys = ['some secret hurr']; const CONFIG = { key: 'koa:sess', /** (string) cookie key (default is koa:sess) */ /** (number || 'session') maxAge in ms (default is 1 days) */ /** 'session' will result in a cookie that expires when session/browser is closed */ /** Warning: If a session cookie is stolen, this cookie will never expire */ maxAge: 86400000, autoCommit: true, /** (boolean) automatically commit headers (default true) */ overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */ renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/ }; app.use(session(CONFIG, app)); // or if you prefer all default config, just use => app.use(session(app)); app.use(ctx => { // ignore favicon if (ctx.path === '/favicon.ico') return; let n = ctx.session.views || 0; ctx.session.views = ++n; ctx.body = n + ' views'; }); app.listen(3000); console.log('listening on port 3000'); ~~~ # [koa-jwt](https://github.com/koajs/jwt) 随着网站前后端分离方案的流行,越来越多的网站从Session Base转为使用Token Base,JWT(Json Web Tokens)作为一个开放的标准被很多网站采用,koa-jwt这个中间件使用JWT认证HTTP请求。 ## Example ~~~js var Koa = require('koa'); var jwt = require('koa-jwt'); var app = new Koa(); // Custom 401 handling if you don't want to expose koa-jwt errors to users app.use(function(ctx, next){ return next().catch((err) => { if (401 == err.status) { ctx.status = 401; ctx.body = 'Protected resource, use Authorization header to get access\n'; } else { throw err; } }); }); // Unprotected middleware app.use(function(ctx, next){ if (ctx.url.match(/^\/public/)) { ctx.body = 'unprotected\n'; } else { return next(); } }); // Middleware below this line is only reached if JWT token is valid app.use(jwt({ secret: 'shared-secret' })); // Protected middleware app.use(function(ctx){ if (ctx.url.match(/^\/api/)) { ctx.body = 'protected\n'; } }); app.listen(3000); ~~~ Alternatively you can conditionally run the`jwt`middleware under certain conditions: ~~~js var koa = require('koa'); var jwt = require('koa-jwt'); var app = new Koa(); // Middleware below this line is only reached if JWT token is valid // unless the URL starts with '/public' app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] })); // Unprotected middleware app.use(function(ctx, next){ if (ctx.url.match(/^\/public/)) { ctx.body = 'unprotected\n'; } else { return next(); } }); // Protected middleware app.use(function(ctx){ if (ctx.url.match(/^\/api/)) { ctx.body = 'protected\n'; } }); app.listen(3000); ~~~ # [koa-helmet](https://github.com/venables/koa-helmet) 网络安全得到越来越多的重视,koa-helmet 通过增加如Strict-Transport-Security, X-Frame-Options, X-Frame-Options等HTTP头提高Koa应用程序的安全性。 ## Example ~~~js "use strict"; const Koa = require("koa"); const helmet = require("koa-helmet"); const app = new Koa(); app.use(helmet()); app.use((ctx) => { ctx.body = "Hello World" }); app.listen(4000); ~~~ # [koa-compress](https://github.com/koajs/compress) 当响应体比较大时,我们一般会启用类似Gzip的压缩技术减少传输内容,koa-compress提供了这样的功能,可根据需要进行灵活的配置。 ## Example ~~~js var compress = require('koa-compress') var Koa = require('koa') var app = new Koa() app.use(compress({ filter: function (content_type) { return /text/i.test(content_type) }, threshold: 2048, flush: require('zlib').Z_SYNC_FLUSH })) ~~~ # [koa-logger](https://github.com/koajs/logger) koa-logger提供了输出请求日志的功能,包括请求的url、状态码、响应时间、响应体大小等信息,对于调试和跟踪应用程序特别有帮助。 ## Example ~~~js const logger = require('koa-logger') const Koa = require('koa') const app = new Koa() app.use(logger()) ~~~ # @koa/cors ## Installation ~~~shell $ npm install @koa/cors@2 --save ~~~ ## Quick start Enable cors with default options: * origin: request Origin header * allowMethods: GET,HEAD,PUT,POST,DELETE,PATCH ~~~js const Koa = require('koa'); const cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); ~~~ # moment 时间格式化 `https://www.npmjs.com/package/moment`