Koa2框架快速入门与基本使用方式

这篇文章主要介绍了Koa2框架快速入门与基本使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

本篇我们讲一下 Koa2 框架的基本使用,希望能帮助大家快速上手

Koa2 是什么?简单来讲,它是一个基于 Node.js 的 web server 框架。

官方文档

Koa2框架使用入门

不使用脚手架,直接使用Koa框架:

# 新建文件夹,控制台进入文件夹 npm init npm install koa 

然后就可以新建js文件写Koa代码了。

带有详细注释的示例代码如下。

const Koa = require('koa') const app = new Koa() // ctx: context, 上下文 app.use((ctx) => { ctx.body = 'hello koa!' // ctx.body即为HTTP响应返回的数据(即响应体中携带的数据) }) app.listen(3000) // 监听3000端口 // 浏览器地址栏输入 http://localhost:3000/ 

使用脚手架koa-generator创建Koa项目:

# 安装脚手架 npm install koa-generator -g # 查看是否安装成功 koa2 --version # 或 koa --version # 在当前路径下的指定文件夹创建koa项目(如果指定文件夹不存在则会创建) koa2  # 比如 koa2 demo # 或者 koa ,如果使用 koa  则创建的是koa1的项目 # 进入以上指定的文件夹,执行 npm install cd  npm install # 开发环境下启动项目 npm run dev # 浏览器访问,地址栏输入如下url(默认端口号3000) http://localhost:3000/ 

Koa2入门示例:新建路由、处理HTTP请求。带有详细注释的示例代码如下。

在routes文件夹下新建文件demo.js如下

// /routes/demo.js const router = require('koa-router')() router.prefix('/demo') // 路径前缀 router.get('/', function (ctx) { // ctx即context,是req(request)和res(response)的集合 const query = ctx.query // 获取url中的参数(以对象的形式表示) console.log('query: ', query); // query: { xxx: 'xxx', ... } ctx.body = 'this is get demo' // 返回数据 }) router.post('/', function (ctx) { const requestBody = ctx.request.body // 获取请求体中的数据 console.log('request body: ', requestBody); // Koa会根据返回的数据的格式自动设置content-type // ctx.body = 'this is post demo' // 自动设置为text/plain ctx.body = { errno: 0, message: 'this is post demo' } // 自动设置为application/json }) module.exports = router 

在app.js文件下引入路由并且注册路由

// /app.js // 引入路由 const demo = require('./routes/demo') // 注册路由 app.use(demo.routes(), demo.allowedMethods()) 

Postman发送POST请求

image.png-600

中间件与洋葱圈模型

中间件: 是指在整体流程上的一个独立的业务模块,其特点是可扩展、可插拔,就类似于工厂流水线中的一道工序。

使用中间件的意义:

  • 有助于将业务进行模块化拆分,让代码易写易读且便于维护;
  • 统一使用中间件,有助于各业务代码的规范化与标准化;
  • 易添加、易删除、易扩展。

对于Koa2框架来讲:

  • 所有的app.use(...)都是中间件;
  • 中间件的回调函数不会在服务启动后立即执行,而是只有当收到网络请求后才会按照顺序执行;
  • 路由也是中间件的一种,当收到网络请求后会根据请求的methodurl进行匹配,执行对应路由的回调函数。

Koa2中间件的回调函数通常具有如下形式:

async (ctx, next) => { // ctx即context,是req(request)和res(response)的集合 // 执行next()即相当于调用下一个中间件的回调函数 // 为了让代码按照预期顺序执行,通常使用 await next() 的方式进行使用 } 

Koa2框架的中间件的执行机制,即为洋葱圈模型:

区分中间件与洋葱圈模型: 中间件是Koa2框架中的业务模块划分,洋葱圈模型是中间件的执行机制(执行顺序)。

洋葱圈模型演示:

// 洋葱圈模型示例代码 const Koa = require('koa') const app = new Koa() app.use(async (ctx, next) => { console.log('1 start') await next() console.log('1 end') }) app.use(async (ctx, next) => { console.log('2 start') await next() console.log('2 end') }) app.use(async (ctx, next) => { console.log('3 start') ctx.body = 'hello world' console.log('3 end') }) app.listen(3000) console.log('server is running') // 启动服务时,控制台打印: // server is running // 浏览器访问 http://localhost:3000/ 后,控制台打印: // 1 start // 2 start // 3 start // 3 end // 2 end // 1 end 

若某一中间件中不调用next(),则其后的所有中间件都不会执行。

// 某一中间件不调用next() const Koa = require('koa') const app = new Koa() app.use((ctx, next) => { console.log('1 start') next() console.log('1 end') }) app.use(async (ctx, next) => { console.log('2 start') // await next() console.log('2 end') }) app.use(async (ctx, next) => { console.log('3 start') ctx.body = 'hello world' console.log('3 end') }) app.listen(3000) console.log('server is running') // 启动服务时,控制台打印: // server is running // 浏览器访问 http://localhost:3000/ 后,控制台打印: // 1 start // 2 start // 2 end // 1 end // 且浏览器不会显示 hello world 

中间件回调函数使用async定义,且next()前加await的意义在于如果后面的中间件中有异步操作(比如Promise),则能保证代码按照期望的顺序执行。

不加async/await示例代码及运行结果:

// 不加async/await const Koa = require('koa') const app = new Koa() app.use((ctx, next) => { console.log('1 start') next() console.log('1 end') }) app.use(() => { console.log('2 start') new Promise((resolve, reject) => { setTimeout(() => { resolve('hello') }, 0) }) .then((data) => { console.log(data) }) .then((data) => { console.log(data) }) console.log('2 end'); }) app.listen(3000) // 浏览器访问 http://localhost:3000/ 后,控制台打印: // 1 start // 2 start // 2 end // 1 end // hello // undefined 

async/await示例代码及运行结果:

const Koa = require('koa') const app = new Koa() app.use(async (ctx, next) => { console.log('1 start') await next() console.log('1 end') }) app.use(async () => { console.log('2 start') await new Promise((resolve, reject) => { setTimeout(() => { resolve('hello') }, 0) }) .then((data) => { console.log(data) }) .then((data) => { console.log(data) }) console.log('2 end'); }) app.listen(3000) // 浏览器访问 http://localhost:3000/ 后,控制台打印: // 1 start // 2 start // hello // undefined // 2 end // 1 end 

总结

至此,Koa2的入门使用就介绍完了~

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。

以上就是Koa2框架快速入门与基本使用方式的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程