Koa2基本用法

安装

因为需要部分ES2015的特性的支持,Koa需要node v4.0.0或更高版本。

cnpm i koa@next

中间件

Koa是一个中间件框架,可以接受三种不同类弄的函数作为中间件:

  • 普通函数
  • async函数
  • generator函数

下面是一个使用不同类型函数作为日志记录中间件的例子:

普通函数

正常情况下中间件接受两个参数(ctx, next),ctx是请求的上下文,next是能引发下游中间件函数的执行,它会返回一个Promise对象。

'use strict';

const Koa = require('koa');
const app = new Koa();

app.use((ctx, next) => {
    const start = new Date();
    return next().then(() => {
        const ms = new Date() - start;
        console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
    });
});

app.use(ctx => {
    ctx.body = 'Hello Koa';
});

app.listen(3000);
console.log('app started at port 3000');

async函数(需要Babel)

对于Node 4.0和Babel 6.0,可以通过以下方式编绎。

cnpm i babel-register babel-plugin-transform-async-to-generator --save
// start.js
'use strict';

// http://babeljs.io/docs/setup/#babel_register

require('babel-register')({
    plugins: ['transform-async-to-generator']
});
require('./app.js');
// app.js
'use strict';

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

app.use(async (ctx) => {
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});

app.listen(3000);
console.log('app started at port 3000');

Generator函数

为了使用generator函数,需要使用co这样的wrapper。

cnpm i co --save
'use strict';

const Koa = require('koa');
const app = new Koa();
const co = require('co');

app.use(co.wrap(function *(ctx, next) {
    const start = new Date();
    yield next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}));

app.use(co.wrap(function *(ctx) {
    ctx.body = 'Hello Koa';
}));

app.listen(3000);
console.log('app started at port 3000');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容