koa 阮一峰koa

1. 路由


1.1 原生路由


  1. // 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
  2. const Koa = require('koa');
  3. // 创建一个Koa对象表示web app本身:
  4. const app = new Koa();
  5. // 对于任何请求,app将调用该异步函数处理请求
  6. const main = (ctx,next) => {
  7. if (ctx.request.path !== '/') {
  8. // 设置response的Content-Type:
  9. ctx.response.type = 'html';
  10. // 设置response的内容
  11. ctx.response.body = '<a href="/">Index Page</a>';
  12. } else {
  13. ctx.response.body = 'Hello World';
  14. }
  15. };
  16. app.use(main);
  17. app.listen(3000);
  • 其中,参数ctx是由koa传入的封装了request和response的变量,我们可以通过它访问request和response,next是koa传入的将要处理的下一个异步函数。

1.2 koa-route 模块

  1. const route = require('koa-route');
  2. const about = ctx => {
  3. ctx.response.type = 'html';
  4. ctx.response.body = '<a href="/">Index Page</a>';
  5. };
  6. const main = ctx => {
  7. ctx.response.body = 'Hello World';
  8. };
  9. app.use(route.get('/', main));
  10. app.use(route.get('/about', about));

2. 静态资源

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

  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const path = require('path');
  4. const serve = require('koa-static');
  5. const main = serve(path.join(__dirname));
  6. app.use(main);
  7. app.listen(3000);

3. 重定向

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

  1. const Koa = require('koa');
  2. const route = require('koa-route');
  3. const app = new Koa();
  4. const redirect = ctx => {
  5. ctx.response.redirect('/');
  6. };
  7. const main = ctx => {
  8. ctx.response.body = 'Hello World';
  9. };
  10. app.use(route.get('/', main));
  11. app.use(route.get('/redirect', redirect));
  12. app.use(main);
  13. app.listen(3000);

4. koa中间件


  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const logger = (ctx, next) => {
  4. console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
  5. next();
  6. }
  7. const main = ctx => {
  8. ctx.response.body = 'Hello World';
  9. };
  10. app.use(logger);
  11. app.use(main);
  12. app.listen(3000);

如上代码,logger 函数就叫做’中间件’(middleware),因为它处在HTTP Request 和 HTTP Response 中间,用来实现某种中间件功能。app.use()用来加载中间件。 Koa所有的功能都是通过中间件实现的,以上的代码例子中,main 也是中间件。每个中间件默认接受两个参数,第一个参数是Context对象,第二个参数是next函数。只要调用next函数,就可以把执行权交给下一个中间件。

4.1 中间件栈


image.pngimage.png

多个中间件会形成一个栈结构(middle stack),以’先进后出’(first-in-last-out)的顺序执行

  1. 1. 最外层的中间件首先执行。
  2. 2. 调用next函数,把执行权交给下一个中间件。
  3. 3. ...
  4. 4. 最内层的中间件最后执行。
  5. 5. 执行结束后,把执行权交回上一层的中间件。
  6. 6. ...
  7. 7. 最外层的中间件收回执行权之后,执行next函数后面的代码。
  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const one = (ctx, next) => {
  4. console.log('>> one');
  5. next();
  6. console.log('<< one');
  7. }
  8. const two = (ctx, next) => {
  9. console.log('>> two');
  10. next();
  11. console.log('<< two');
  12. }
  13. const three = (ctx, next) => {
  14. console.log('>> three');
  15. next();
  16. console.log('<< three');
  17. }
  18. app.use(one);
  19. app.use(two);
  20. app.use(three);
  21. app.listen(3000);

输出结果:

  1. >> one
  2. >> two
  3. >> three
  4. << three
  5. << two
  6. << one

4.2 异步中间件

  1. const fs = require('fs.promised');
  2. const Koa = require('koa');
  3. const app = new Koa();
  4. const main = async function (ctx, next) {
  5. ctx.response.type = 'html';
  6. ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');
  7. };
  8. app.use(main);
  9. app.listen(3000);

4.3 中间件的合成

  1. const Koa = require('koa');
  2. const compose = require('koa-compose');
  3. const app = new Koa();
  4. const logger = (ctx, next) => {
  5. console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
  6. next();
  7. }
  8. const main = ctx => {
  9. ctx.response.body = 'Hello World';
  10. };
  11. const middlewares = compose([logger, main]);
  12. app.use(middlewares);
  13. app.listen(3000);

5. 错误处理


5.1 500 错误

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

  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const main = ctx => {
  4. ctx.throw(500);
  5. };
  6. app.use(main);
  7. app.listen(3000);

5.2 404错误

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

  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const main = ctx => {
  4. ctx.response.status = 404;
  5. ctx.response.body = 'Page Not Found';
  6. };
  7. app.use(main);
  8. app.listen(3000);

中间件 抛错 捕获

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

  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const handler = async (ctx, next) => {
  4. try {
  5. await next();
  6. } catch (err) {
  7. ctx.response.status = err.statusCode || err.status || 500;
  8. ctx.response.body = {
  9. message: err.message
  10. };
  11. }
  12. };
  13. const main = ctx => {
  14. ctx.throw(500);
  15. };
  16. app.use(handler);
  17. app.use(main);
  18. app.listen(3000);

访问 http://127.0.0.1:3000 ,你会看到一个500页,里面有报错提示 {“message”:”Internal Server Error”}。

释放 error 事件

需要注意的是,如果错误被try…catch捕获,就不会触发error事件。这时,必须调用ctx.app.emit(),手动释放error事件,才能让监听函数生效

  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const handler = async (ctx, next) => {
  4. try {
  5. await next();
  6. } catch (err) {
  7. ctx.response.status = err.statusCode || err.status || 500;
  8. ctx.response.type = 'html';
  9. ctx.response.body = '<p>Something wrong, please contact administrator.</p>';
  10. ctx.app.emit('error', err, ctx);
  11. }
  12. };
  13. const main = ctx => {
  14. ctx.throw(500);
  15. };
  16. app.on('error', function(err) {
  17. console.log('logging error ', err.message);
  18. console.log(err);
  19. });
  20. app.use(handler);
  21. app.use(main);
  22. app.listen(3000);

上面代码中,main函数抛出错误,被handler函数捕获。catch代码块里面使用ctx.app.emit()手动释放error事件,才能让监听函数监听到。