介绍

koa,是基于Node.js 平台的下一代的web开发框架。
是由Express原班人马打造,致力于成为一个更小的,更加富裕表现力的,web框架。
应用koa编写web利用,能够罢黜反复的回调函数嵌套,并极大的进步错误处理的效率,
koa框架不仅仅在内核办法中能够绑定任何中间件,它仅仅提供了一个轻量级,优雅的函数库,思路和express相差不少。

koa框架的装置

装置koa

装置koa框架和装置之前的模块一样。
应用如下命令装置

npm install --save koa

应用save参数,表明将会主动批改package.json 文件。主动增加依赖项

hello world

输出如下的代码,运行hello world

const koa = require("koa");const app = new koa();// 配置中间件app.use(async (ctx) => {    ctx.body = "hello world";})// 监听端口app.listen(3000);

运行文件

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js

输入后果如下

异步的解决

因为js是单线程的,所以,应用回调函数解决异步等问题。

回调函数解决

const koa = require("koa");const app = new koa();function getData(callback){    setTimeout(function () {        var name = "ming";        callback(name);    }, 1000)}// 从内部获取异步办法里的数据getData(function (data) {    console.log(data)})// 监听端口app.listen(3000);

输入后果

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.jsming

应用promise解决异步

const koa = require("koa");const app = new koa();// promise 解决异步// resolve 胜利的回调函数// reject 失败的回调函数var p = new Promise(function (resolve, reject) {    setTimeout(function () {        var name = "张三";    }, 1000)})// 获取异步的后果p.then((data) => {    console.log(data);}) // 监听端口app.listen(3000);

运行后果如下

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.jsming

对于async await promise

其中async是异步的缩写,await被认为是async wait的缩写,所以,async用于申明一个函数为异步的,await用于期待一个异步办法执行实现。

简略了解

async 让办法变成异步
await 期待异步办法执行实现。

async

理论例子

这里应用理论的例子,更好了解。

同步函数

function getData(){    return "ming";}console,log(getData())

输入后果

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.jsming

async 能够让该办法变成异步

const koa = require("koa");const app = new koa();// promise 解决异步// resolve 胜利的回调函数// reject 失败的回调函数async function getData(){    return "这是一个数据";}console.log(getData());// 监听端口app.listen(3000);

输入后果如下所示

其中promise为一个异步的数据

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.jsPromise { '这是一个数据' }

获取该数据

const koa = require("koa");const app = new koa();// promise 解决异步// resolve 胜利的回调函数// reject 失败的回调函数async function getData(){    return "这是一个数据";}var p = getData();p.then((data) => {    console.log(data);})// 监听端口app.listen(3000);

输入后果如图所示

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js这是一个数据

await

应用await办法获取到异步的信息

const koa = require("koa");const app = new koa();// promise 解决异步// resolve 胜利的回调函数// reject 失败的回调函数async function getData(){    return "这是一个数据";}async  function test(){    // 此时运行的为,发现该函数是一个异步函数,遇到了await进入期待状态,期待getData执行结束,再往下执行    var d = await  getData();    console.log(d)}test()// 监听端口app.listen(3000);

运行后果

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js这是一个数据

koa 路由

路由是依据不同的url地址,加载不同页面实现不同的性能。

装置路由

 npm install --save koa-router

应用路由

const koa = require("koa");const app = new koa();const router = require("koa-router")();router.get("/", (ctx, next) => {    ctx.body = "ming";})// 启动路由app.use(router.routes());app.use(router.allowedMethods());// 监听端口app.listen(3000);

运行后果如下所示

其中能够增加async作为异步办法来调用

const koa = require("koa");const app = new koa();const router = require("koa-router")();router.get("/", async (ctx, next) => {    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

获取链接的参数值

通过router获取路由的参数值
链接为

获取格式化好的

http://localhost:3000/?ming=3

代码为

const koa = require("koa");const app = new koa();const router = require("koa-router")();router.get("/", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.query)    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

拜访的后果是

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js[Object: null prototype] { ming: '3' }

获取未格式化好的

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.jsming=3
const koa = require("koa");const app = new koa();const router = require("koa-router")();router.get("/", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.querystring)    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

设置动静路由

const koa = require("koa");const app = new koa();const router = require("koa-router")();// 配置动静路由router.get("/:id", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.params)    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

拜访的链接为

http://localhost:3000/ming

输入的内容

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js{ id: 'ming' }

koa 中间件

这里配置koa的中间件
中间件就是匹配路由实现做的一系列的操作,把它称之为中间件。

中间件的性能次要有:

  1. 执行任何代码
  2. 批改申请和响应的对象
  3. 终结申请,响应循环
  4. 调用堆栈中的下一个中间件。

需要: 打印出中间件相干内容

const koa = require("koa");const app = new koa();const router = require("koa-router")();// 中间件app.use(async (ctx) => {    ctx.body = "这是一个中间件";})// 配置动静路由router.get("/:id", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.params)    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

运行后果

此时拜访任何页面呈现的都是这个内容,

继续匹配

因为拜访的时候,没有加上next,此时造成的无奈进入到匹配路由的阶段。

const koa = require("koa");const app = new koa();const router = require("koa-router")();// 中间件app.use(async (ctx, next) => {    ctx.body = "这是一个中间件";    // 进入路由匹配    next();})// 配置动静路由router.get("/:id", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.params)    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

因为js是单线程的,此时须要增加await,进行拜访。

const koa = require("koa");const app = new koa();const router = require("koa-router")();// 中间件app.use(async (ctx, next) => {    ctx.body = "这是一个中间件";    // 进入路由匹配    await next();})// 配置动静路由router.get("/:id", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.params)    ctx.body = "ming";})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

路由继续匹配

路由因为没有await next,造成路由匹配到当前就不再匹配,所以增加next,能把两个雷同的路由依照程序,匹配实现。

const koa = require("koa");const app = new koa();const router = require("koa-router")();// 中间件app.use(async (ctx, next) => {    ctx.body = "这是一个中间件";    // 进入路由匹配    await next();})// 配置动静路由router.get("/:id", async (ctx, next) => {    // query 返回的是格式化好的参数对象    // querystring 返回的是申请的字符串    console.log(ctx.params)    ctx.body = "ming";        await next();})router.get("/:id", async (ctx, next) => {    // 此时匹配到这点    await  next();})// 启动路由app.use(router.routes());// 设置响应头app.use(router.allowedMethods());// 监听端口app.listen(3000);

中间件的执行程序

个别是洋葱模型,作为中间件的执行程序。

错误处理中间件

// 中间件app.use(async (ctx, next) => {    console.log("这是一个中间件");        // 进入洋葱    next()        // 出洋葱    if(ctx.status = 404){        ctx.status = 404;        ctx.body = "这是一个 404 页面";    }})

第三方中间件

例如进行动态文件托管的时候,应用的是第三方中间件

const static = require('koa-static');const staticPath = './static';app.use(static(    path.join(__dirname, staticPath);))const bodyParser = require('koa-bodyparser');app.use(bodyParser());

这样就实现了动态文件托管