A Koa application is an object containing an array of middleware functions which are composed and executed in a stack-like manner upon request. Koa is similar to many other middleware systems that you may have encountered such as Ruby's Rack, Connect, and so on - however a key design decision was made to provide high level "sugar" at the otherwise low-level middleware layer. This improves interoperability, robustness, and makes writing middleware much more enjoyable.
Koa 在2017-02-25 发布了2.0 版本,详情请参照git hub 上history.md
1.0 与2.0 版本关于中间件的异同
1.0 版本是通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升错误处理的效率。
2.0版本Koa放弃了generator,采用Async 函数实现组件数组瀑布流式(Cascading)的开发模式。
先来看看Koa 2.0 版本Hello word的demo,
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Koa中间件的方式
Common function
/* Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
next is a function that is invoked to execute the downstream middleware.
It returns a Promise with a then function for running code after completion. */
app.use((ctx, next) => {
const start = new Date();
return next().then(() => {
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
Async function
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
async与common function 的区别主要在于语法糖面前是否存在async,如果需要同步的执行中间件或是函数,只需要在中间件或函数前加关键字await。
// 同步执行中间件
app.use(async (ctx, next) => { await next(); });
Koa Cascading 中间件值的传递
Middleware1 中间件中的函数next()返回的是一个promise 对像
const Koa = require('koa');
const app = new Koa();
//Middleware 1
app.use(async function (ctx, next) {
console.log("1.1")
await next().then(function (data) {
console.log(data) // "Spursyy"
}).catch(function (err) {
console.log(err)
});
console.log("1.2")
})
//Middleware 2
app.use(async function (ctx, next) {
return new Promise (function (resolve, reject) {
resolve("Spursyy")
})
})
app.listen(3000);
console.log("port 3000 was start!")