
注:以下学习笔记来自阮一峰的《Koa框架教程》(相关链接见本文末尾),代码亲手敲了一遍,自我消化后的笔记摘抄与再整理。
Koa 就是一种简单好用的 Web 框架。它的特点是优雅、简洁、表达力强、自由度高。本身代码只有1000多行,所有功能都通过插件实现,很符合 Unix 哲学。
一、使用Koa 架设一个 HTTP 服务

二、Context 对象
Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。
Context.response.body属性就是发送给用户的内容。ctx.request代表 HTTP Request。
三、HTTP Response 的类型
Koa 默认的返回类型是text/plain,如果想返回其他类型的内容,可以先用ctx.request.accepts判断一下,客户端希望接受什么数据(根据 HTTP Request 的Accept字段),然后使用ctx.response.type指定返回类型。

四、网页模板
实际开发中,返回给用户的网页往往都写成模板文件。我们可以让 Koa 先读取模板文件,然后将这个模板返回给用户。
五、原生路由
网站一般都有多个页面。通过ctx.request.path可以获取用户请求的路径,由此实现简单的路由。

六、使用 Koa-route模块
原生路由用起来不太方便,我们可以使用封装好的koa-route模块。

七、静态资源服务
如果网站提供静态资源(图片、字体、样式表、脚本......),为它们一个个写路由就很麻烦,也没必要。koa-static模块封装了这部分的请求。

八、重定向
有些场合,服务器需要重定向(redirect)访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()方法可以发出一个302跳转,将用户导向另一个路由。

九、中间件
Koa 的最大特色,也是最重要的一个设计,就是中间件(middleware)。因为它处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能,所以叫做“中间件”。app.use()用来加载中间件。
基本上,Koa 所有的功能都是通过中间件实现的。每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是next函数。只要调用next函数,就可以把执行权转交给下一个中间件。

十、中间件栈
多个中间件会形成一个栈结构(middle stack),以"先进后出"(first-in-last-out)的顺序执行。如果中间件内部没有调用next函数,那么执行权就不会传递下去。

十一、异步中间件
如果有异步操作(比如读取数据库),中间件就必须写成 async 函数。且异步操作前面也必须加上await关键字。

十二、中间件合成
koa-compose模块可以将多个中间件合成为一个。

十三、500 错误
如果代码运行过程中发生错误,我们需要把错误信息返回给用户。HTTP 协定约定这时要返回500状态码。Koa 提供了ctx.throw()方法,用来抛出错误,ctx.throw(500)就是抛出500错误。

十四、404 错误
如果将ctx.response.status设置成404,就相当于ctx.throw(404),返回404错误。

十五、错误处理中间件
为了方便处理错误,最好使用try...catch将其捕获。但是,为每个中间件都写try...catch太麻烦,我们可以让最外层的中间件,负责所有中间件的错误处理。

十六、error 事件监听与事件释放
运行过程中一旦出错,Koa 会触发一个error事件。监听这个事件,也可以处理错误。
需要注意的是,如果错误被try...catch捕获,就不会触发error事件。这时,必须调用ctx.app.emit(),手动释放error事件,才能让监听函数生效。

十七、Cookie
ctx.cookies用来读写 Cookie。

十八、表单处理
Web 应用离不开处理表单。本质上,表单就是 POST 方法发送到服务器的键值对。koa-body模块可以用来从 POST 请求的数据体里面提取键值对。

十九、文件上传
koa-body模块还可以用来处理文件上传。

参考资源:
1、阮一峰博客:http://www.ruanyifeng.com/blog/2017/08/koa.html
2、Koa官网:http://koajs.com/

网友评论