介绍

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.js
ming

使用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.js
ming

关于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.js
ming

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.js
Promise { '这是一个数据' }

获取该数据

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.js
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.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);

运行结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ERHiKkny-1594813455965)(https://www.iming.info/wp-content/uploads/2020/07/wp_editor_md_758be669b72a1ca132c7aea9629a4cf0.jpg)]

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

持续匹配

因为访问的时候,没有加上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());

这样就完成了静态文件托管

知新 | koa框架入门到熟练第一章相关推荐

  1. 知新 | koa框架入门到熟练第二章

    koa-bodyparser 使用 这里对koa-bodyparser的使用教程. 目录如下 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Madk1tVn-15949 ...

  2. ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区

    原文:ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区 1 引言 1.1 读者定位 我们假设用户在阅读本指南前应已具备以下知识: · 熟悉W ...

  3. R语言学习笔记——入门篇:第一章-R语言介绍

    R语言 R语言学习笔记--入门篇:第一章-R语言介绍 文章目录 R语言 一.R语言简介 1.1.R语言的应用方向 1.2.R语言的特点 二.R软件的安装 2.1.Windows/Mac 2.2.Lin ...

  4. D3.js的v5版本入门教程(第一章)—— 如何在项目中使用D3.js

    D3.js的v5版本入门教程(第一章) 1.需要的一些工具 这个其实随便!最简单的就是建一个.txt文件就可以敲起代码来!作者本人用的是myeclipse(主要需要安装tomcat),因为写的是前端, ...

  5. HT合泰单片机入门教程(第一章 HT单片机环境搭建)

    目录 系列文章目录 前言 一.合泰单片机的优势 二.IDE安装 1.HT-IDE3000下载 2.HT-IDE3000安装 三.烧录软件安装 1.HOPE3000下载 2.HOPE3000安装 总结 ...

  6. 萌新向Python数据分析及数据挖掘 第一章 Python基础 第三节 列表简介 第四节 操作列表...

    第一章 Python基础 第三节 列表简介 列表是是处理一组有序项目的数据结构,即可以在一个列表中存储一个序列的项目.列表中的元素包括在方括号([])中,每个元素之间用逗号分割.列表是可变的数据类型, ...

  7. y2第一章 初始mybatis的上机3_MyBatis3.2.x从入门到精通之第一章

    第一章 一.引言 mybatis是一个持久层框架,是apache下的顶级项目.mybatis托管到goolecode下,再后来托管到github下.(百度百科有解释) 二.概述 mybatis让程序将 ...

  8. SpringMVC从入门到精通之第一章_慕课文章

    第一节 简介: SpringMVC是Spring框架的一个模块,Spring和SpringMVC无需通过中间整合层进行整合. SpringMVC是基于MVC的WEB框架. MVC设计模式在B/S下的应 ...

  9. python数据挖掘入门与实践-第一章-用最简单OneR算法对Iris植物分类

    前言: 这本书其实有配套代码的来着,但是有点坑的是,里面的代码对应的版本是有点旧的,用的时候会警告或者已经报错.甚至有些代码书里提了但是却没有写进去,要自己去摸索.我是每一章都跟着代码示例,把每一个步 ...

最新文章

  1. AAAI 2021线下论文预讲会讲者征集
  2. Activity栈管理(三):Intent的Flag与taskAffinity
  3. CTFshow 命令执行 web119
  4. 马云缺席的一个半小时,李彦宏和马化腾都聊了什么
  5. 一个多版本IE共存软件 IETester(支持IE5.5,6,7,8Beta1)
  6. JZOJ 5353. 【NOIP2017提高A组模拟9.9】村通网
  7. Linux设备驱动开发-linux驱动中的阻塞访问方式
  8. struts2找不到action_第一次用上Struts2框架做Web开发的体验……
  9. c++进制转换代码_轻松实现C/C++各种常见进制相互转换,你还不会你就落后了
  10. 会话(session)
  11. 年少恶习累累,成年用语言骗全世界, 用心理学撩妹, 最后被总理接见
  12. jq mysql二级联动_jq+php+mysql 实现二级菜单联动
  13. Matplotlib 绘图秘籍
  14. 网易互娱基于 Flink 的支付环境全关联分析实践
  15. 各种格式的地图瓦片下载
  16. Windows API函数大全(1)
  17. Jenkins--发送邮件配置
  18. JAVA WEB 复习资料
  19. Floating point exception (core dumped)解决
  20. java 滚动歌词_基于JavaScript怎么实现让歌词滚动播放

热门文章

  1. Celery 源码解析六:Events 的实现
  2. 《Servlet和JSP学习指南》一导读
  3. AD-批量启用账户命令 Enable-adaccount
  4. jvm学习笔记(3)——java对象的内存分配和对象的回收(GC)
  5. GTN-Graph Transformer Network 图变换网络 NeurIPS2019
  6. Payroll Calculation的Process Rule
  7. Android多线程之IntentService源码解析
  8. 商家为什么要接受BCH支付?
  9. Spring boot Scheduled 配置
  10. 一个简单的主机管理模拟程序