koa2入门学习

时间:2022-05-10
本文章向大家介绍koa2入门学习,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

koa模块

koa-route 路由 route.get("路径",路由函数)

koa-static 静态资源加载     const serve(路径)

koa-compose  中间件合成模块

koa-body   提取表单post请求键值对,处理上传文件

上下文context的response和request

ctx.response.body   //返回的主体内容

ctx.response.redirect //重定向

ctx.response.type   //返回的MIME类型

ctx.response.path  //获取用户请求的路径

ctx.response.status  //返回的状态码

ctx.request.accepts //请求的mime类型

ctx.request.method //请求的方法

ctx.request.url         //请求的url

ctx.request.body //请求的body

中间件(middleware)

Logger 打印日志 //不需要引入任何,直接输入console.log,在命令框就会打印出来

中间件功能可以拆分成一个独立函数比如叫logger,参数(ctx,next) 然后app.use(logger),用来加载中间件

基本上,Koa 所有的功能都是通过中间件实现的,前面例子里面的main也是中间件。

每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是next函数。

只要调用next函数,就可以把执行权转交给下一个中间件。

中间件栈

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

  1. 最外层的中间件首先执行。
  2. 调用next函数,把执行权交给下一个中间件。
  3. ...
  4. 最内层的中间件最后执行。
  5. 执行结束后,把执行权交回上一层的中间件。
  6. ...
  7. 最外层的中间件收回执行权之后,执行next函数后面的代码。

例如:有多个中间件,每个中间件分别写了next()函数,则每个中间件会分别先执行next()函数之前的打印,然后再分别执行next()之后的打印,如果不写next()函数,那么执行权就不会传递下去,则只打印第一个中间件的内容。

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);
>> one
>> two
>> three
<< three
<< two
<< one
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
<<one
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
<<two
<<one

异步中间件

比如读取数据库等的异步操作,使用ES8 的 async和await

中间件的合成

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

错误处理

ctx.throw()方法   参数为错误的http状态码

当直接用ctx.throw()抛出错误之后,则不能在定义返回的页面显示内容,所以可以先设置返回的状态码为相应的状态码,然后定义返回页面的内容

const main = ctx => {
  ctx.response.status = 404;
  ctx.response.body = 'Page Not Found';
};

处理错误的中间件

使用try..catch捕获

try{

  await next()

}catch{

  错误处理

}

error 事件的监听

运行过程中一旦出错,Koa 会触发一个error事件。监听这个事件,也可以处理错误。

释放 error 事件

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

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);
});

Cookies

ctx.cookies用来读写 Cookie。

表单

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

文件上传

参考链接:阮一峰老师的文章