首先,咱们建立一个目录hello-koa
并做为工程目录用VS Code打开。而后,咱们建立app.js
,输入如下代码:html
// 导入koa,和koa 1.x不一样,在koa2中,咱们导入的是一个class,所以用大写的Koa表示: const Koa=require('koa2'); // 建立一个Koa对象表示web app自己: const app = new Koa(); // 对于任何请求,app将调用该异步函数处理请求: app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, koa2!</h1>'; }); // 在端口3000监听: app.listen(3000); console.log('app started at port 3000...'); //能够在http://127.0.0.1:3000访问
对于每个http请求,koa将调用咱们传入的异步函数来处理:node
async (ctx, next) => { await next(); // 设置response的Content-Type: ctx.response.type = 'text/html'; // 设置response的内容: ctx.response.body = '<h1>Hello, koa2!</h1>'; }
其中,参数ctx
是由koa传入的封装了request和response的变量,咱们能够经过它访问request和response,next
是koa传入的将要处理的下一个异步函数。web
上面的异步函数中,咱们首先用await next();
处理下一个异步函数,而后,设置response的Content-Type和内容。npm
由async
标记的函数称为异步函数,在异步函数中,能够用await
调用另外一个异步函数,这两个关键字将在ES7中引入。数组
廖老师官网上还探讨了koa2这个包怎么装,可是如今koa2已经嵌入了node中,不用另外npm安装,这里就忽略了,直接用require在项目中引入使用便可。app
让咱们再仔细看看koa的执行逻辑。核心代码是:koa
app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, koa2!</h1>'; });
每收到一个http请求,koa就会调用经过app.use()
注册的async函数,并传入ctx
和next
参数。异步
咱们能够对ctx
操做,并设置返回内容。可是为何要调用await next()
?async
缘由是koa把不少async函数组成一个处理链,每一个async函数均可以作一些本身的事情,而后用await next()
来调用下一个async函数。咱们把每一个async函数称为middleware,这些middleware能够组合起来,完成不少有用的功能。函数
例如,能够用如下3个middleware组成处理链,依次打印日志,记录处理时间,输出HTML:
app.use(async (ctx, next) => { console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL await next(); // 调用下一个middleware }); app.use(async (ctx, next) => { const start = new Date().getTime(); // 当前时间 await next(); // 调用下一个middleware const ms = new Date().getTime() - start; // 耗费时间 console.log(`Time: ${ms}ms`); // 打印耗费时间 }); app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, koa2!</h1>'; });
middleware的顺序很重要,也就是调用app.use()
的顺序决定了middleware的顺序。
此外,若是一个middleware没有调用await next()
,会怎么办?答案是后续的middleware将再也不执行了。这种状况也很常见,例如,一个检测用户权限的middleware能够决定是否继续处理请求,仍是直接返回403错误:
app.use(async (ctx, next) => { if (await checkUserPermission(ctx)) { await next(); } else { ctx.response.status = 403; } });
理解了middleware,咱们就已经会用koa了!
最后注意ctx
对象有一些简写的方法,例如ctx.url
至关于ctx.request.url
,ctx.type
至关于ctx.response.type
。