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 <directory name> # 比如 koa2 demo
# 或者 koa <directory name>,如果使用 koa <directory name> 则创建的是koa1的项目
    
# 进入以上指定的文件夹,执行 npm install
cd <directory name>
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


中间件与洋葱圈模型

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

使用中间件的意义:

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

对于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的入门使用就介绍完了,希望对大家有所帮助~

如有疏漏之处欢迎评论区留言指正哦~

  • 2
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,你可以使用koa2框架与mysql2库连接和操作数据库。下面是一个简单的示例: 首先,你需要安装所需的依赖: ``` npm install koa koa-router koa-bodyparser mysql2 ``` 然后,在你的项目中创建一个数据库连接配置文件(比如config.js),并填写数据库的相关信息: ```javascript // config.js module.exports = { database: 'your_database_name', username: 'your_username', password: 'your_password', host: 'your_host', port: 'your_port' }; ``` 接下来,创建一个数据库连接池并导出供其他模块使用: ```javascript // db.js const mysql = require('mysql2/promise'); const config = require('./config.js'); const pool = mysql.createPool({ host: config.host, port: config.port, user: config.username, password: config.password, database: config.database, connectionLimit: 10 // 可以根据需要进行调整 }); module.exports = pool; ``` 最后,在你的路由文件中使用数据库连接池来执行查询和操作: ```javascript // routes.js const Router = require('koa-router'); const pool = require('./db.js'); const router = new Router(); router.get('/users', async (ctx) => { try { const [rows] = await pool.query('SELECT * FROM users'); ctx.body = rows; } catch (err) { console.error(err); ctx.status = 500; ctx.body = 'Error occurred while fetching users'; } }); // 其他路由和操作 module.exports = router; ``` 这只是一个简单的示例,你可以根据自己的需求进行更复杂的数据库操作。记得在需要使用数据库连接的地方引入连接池,并根据需要执行查询、插入、更新等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值