16
Koa2 与它的中间件们
source link: http://misaka.im/index.php/archives/48/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Koa2 与它的中间件们
Node.js
reify
Enable ECMAScript 2015 modules in Node today. No caveats. Full stop.
ES6 的模块语法 import
在 node 环境中仍然不兼容,或者说需要 ejs
文件格式。
入口文件使用 reify
解决:
require("reify")
不嫌弃配置麻烦的话,也可以考虑 babel
。
Koa2 需要配合非常多中间件来使用,才能成为一个后端框架。
koa-conditional-get
Conditional Get 又名条件式请求,常见实现有 Last-Modified 和 ETag 两种。
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const Koa = require('koa');
const app = new Koa();
// use it upstream from etag so
// that they are present
app.use(conditional());
// add etags
app.use(etag());
koa-bodyparser
解析 HTTP 主体
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-static
静态服务器
import staticServe from 'koa-static'
app.use(staticServe(path.join(__dirname, '../assets'), {
maxAge: 24 * 60 * 60
}))
koa-views
模板渲染中间件
const views = require('koa-views');
app.use(views(path.join(__dirname, 'views')));
koa-mount
通过 URL 挂载,将其他 Koa 实例挂在到一个主实例中
const a = new Koa();
const b = new Koa();
app.use(mount('/hello', a));
app.use(mount('/world', b));
koa-connect
兼容 Express 中间件可以在 Koa 中使用
import connect from 'koa-connect'
app.use(c2k(connectMiddlware))
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK