koa 阮一峰koa
1. 路由
1.1 原生路由
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:const Koa = require('koa');// 创建一个Koa对象表示web app本身:const app = new Koa();// 对于任何请求,app将调用该异步函数处理请求const main = (ctx,next) => {if (ctx.request.path !== '/') {// 设置response的Content-Type:ctx.response.type = 'html';// 设置response的内容ctx.response.body = '<a href="/">Index Page</a>';} else {ctx.response.body = 'Hello World';}};app.use(main);app.listen(3000);
- 其中,参数
ctx是由koa传入的封装了request和response的变量,我们可以通过它访问request和response,next是koa传入的将要处理的下一个异步函数。
1.2 koa-route 模块
const route = require('koa-route');const about = ctx => {ctx.response.type = 'html';ctx.response.body = '<a href="/">Index Page</a>';};const main = ctx => {ctx.response.body = 'Hello World';};app.use(route.get('/', main));app.use(route.get('/about', about));
2. 静态资源
如果网站提供静态资源(图片、字体、样式表、脚本……),为它们一个个写路由就很麻烦,也没必要。koa-static模块封装了这部分的请求。
const Koa = require('koa');const app = new Koa();const path = require('path');const serve = require('koa-static');const main = serve(path.join(__dirname));app.use(main);app.listen(3000);
3. 重定向
服务器需要重定向(redirect)访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()方法可以发出一个302跳转,将用户导向另一个路由。
const Koa = require('koa');const route = require('koa-route');const app = new Koa();const redirect = ctx => {ctx.response.redirect('/');};const main = ctx => {ctx.response.body = 'Hello World';};app.use(route.get('/', main));app.use(route.get('/redirect', redirect));app.use(main);app.listen(3000);
4. koa中间件
const Koa = require('koa');const app = new Koa();const logger = (ctx, next) => {console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);next();}const main = ctx => {ctx.response.body = 'Hello World';};app.use(logger);app.use(main);app.listen(3000);
如上代码,logger 函数就叫做’中间件’(middleware),因为它处在HTTP Request 和 HTTP Response 中间,用来实现某种中间件功能。app.use()用来加载中间件。 Koa所有的功能都是通过中间件实现的,以上的代码例子中,main 也是中间件。每个中间件默认接受两个参数,第一个参数是Context对象,第二个参数是next函数。只要调用next函数,就可以把执行权交给下一个中间件。
4.1 中间件栈


多个中间件会形成一个栈结构(middle stack),以’先进后出’(first-in-last-out)的顺序执行
1. 最外层的中间件首先执行。2. 调用next函数,把执行权交给下一个中间件。3. ...4. 最内层的中间件最后执行。5. 执行结束后,把执行权交回上一层的中间件。6. ...7. 最外层的中间件收回执行权之后,执行next函数后面的代码。
const Koa = require('koa');const app = new Koa();const one = (ctx, next) => {console.log('>> one');next();console.log('<< one');}const two = (ctx, next) => {console.log('>> two');next();console.log('<< two');}const three = (ctx, next) => {console.log('>> three');next();console.log('<< three');}app.use(one);app.use(two);app.use(three);app.listen(3000);
输出结果:
>> one>> two>> three<< three<< two<< one
4.2 异步中间件
const fs = require('fs.promised');const Koa = require('koa');const app = new Koa();const main = async function (ctx, next) {ctx.response.type = 'html';ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');};app.use(main);app.listen(3000);
4.3 中间件的合成
const Koa = require('koa');const compose = require('koa-compose');const app = new Koa();const logger = (ctx, next) => {console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);next();}const main = ctx => {ctx.response.body = 'Hello World';};const middlewares = compose([logger, main]);app.use(middlewares);app.listen(3000);
5. 错误处理
5.1 500 错误
如果代码运行过程中发生错误,我们需要把错误信息返回给用户。HTTP 协定约定这时要返回500状态码。Koa 提供了ctx.throw()方法,用来抛出错误,ctx.throw(500)就是抛出500错误
const Koa = require('koa');const app = new Koa();const main = ctx => {ctx.throw(500);};app.use(main);app.listen(3000);
5.2 404错误
如果将ctx.response.status设置成404,就相当于ctx.throw(404),返回404错误
const Koa = require('koa');const app = new Koa();const main = ctx => {ctx.response.status = 404;ctx.response.body = 'Page Not Found';};app.use(main);app.listen(3000);
中间件 抛错 捕获
为了方便处理错误,最好使用try…catch将其捕获。但是,为每个中间件都写try…catch太麻烦,我们可以让最外层的中间件,负责所有中间件的错误处理
const Koa = require('koa');const app = new Koa();const handler = async (ctx, next) => {try {await next();} catch (err) {ctx.response.status = err.statusCode || err.status || 500;ctx.response.body = {message: err.message};}};const main = ctx => {ctx.throw(500);};app.use(handler);app.use(main);app.listen(3000);
访问 http://127.0.0.1:3000 ,你会看到一个500页,里面有报错提示 {“message”:”Internal Server Error”}。
释放 error 事件
需要注意的是,如果错误被try…catch捕获,就不会触发error事件。这时,必须调用ctx.app.emit(),手动释放error事件,才能让监听函数生效
const Koa = require('koa');const app = new Koa();const handler = async (ctx, next) => {try {await next();} catch (err) {ctx.response.status = err.statusCode || err.status || 500;ctx.response.type = 'html';ctx.response.body = '<p>Something wrong, please contact administrator.</p>';ctx.app.emit('error', err, ctx);}};const main = ctx => {ctx.throw(500);};app.on('error', function(err) {console.log('logging error ', err.message);console.log(err);});app.use(handler);app.use(main);app.listen(3000);
上面代码中,main函数抛出错误,被handler函数捕获。catch代码块里面使用ctx.app.emit()手动释放error事件,才能让监听函数监听到。
