nodejs详细koa框架学习笔记

Koa

1,KOA的设计思想

  • 基于NodeJs的web框架,致力于web应用和API开发。
  • 由Express 原班人马打造。
  • 支持async。
  • 更小、更灵活、更优雅。

官网:https://koajs.com/
中文官网:https://koa.bootcss.com/

1-1 异步流程控制

koa 采用 async/await

1-2 中间件模型

koa中间件采用洋葱模型(对于每个中间件,在完成一些事情后,可以非常优雅的将控制权传递给下一个中间件,并能够等待它完成,当后续中间件完成处理后,控制权又回到了自己)

2,KOA的安装

#安装 koa
** npm install koa**
#或者
yarn add koa

3. hello world

const Application = require("koa")

const server = new Application()

server.use(async (ctx, next) => {
  // 设置响应状态
  ctx.response.status = 200
  // 设置响应头
  ctx.response.set( { "Content-Type": "text/html", "access-control-allow-origin": "*" })
  
  ctx.response.body = JSON.stringify("hello world")
})

server.listen(8080, () => {
  console.log("Server Start Success  http://localhost:8080")
})


Koa同步与异步执行顺序

同步:

image.png

  const Koa = require("koa")
  const app = new Koa()

  app.use((ctx,next) => {
    console.log("请求")
    if(ctx.request.path === "/home") {
      console.log("11111")
      ctx.response.body = "home页面"
      next()
      console.log("22222")
    }
  })

  app.use((ctx,next) => {
    console.log("33333")
  })
  app.listen(8080)

API

Context 具体方法和访问器.
ctx.req

  • Node 的 request 对象.

ctx.res

  • Node 的 response 对象.

绕过 Koa 的 response 处理是 不被支持的. 应避免使用以下 node 属性:

  • res.statusCode
  • res.writeHead()
  • res.write()
  • res.end()

ctx.request请求 和 ctx.response响应

ctx.request

koa 的 Request 对象

ctx.request.header
ctx.request.headers
ctx.request.method
ctx.request.url
ctx.request.originallUrl
ctx.request.origin
ctx.request.href
ctx.request.path
ctx.request.query
ctx.request.querystring
ctx.request.host
ctx.request.host
ctx.request.hostname

ctx.response

koa 的 Response 对象

ctx.response.body
ctx.response.status
ctx.response.message
ctx.response.length
ctx.response.type
ctx.response.headerSent
ctx.response.redirect()
ctx.response.attachment()
ctx.response.set()
ctx.response.append()
ctx.response.remove()
ctx.response.lastModified
ctx.response.etag

koa-router 路由

文档地址:https://github.com/koajs/router/blob/master/API.md

安装:

npm install koa-router

基本使用
const Koa = require('koa');
const Router = require('koa/router');

const app = new Koa();
const router = new Router();

router.get('/', (ctx, next) => {
  // ctx.router available
});

app
  .use(router.routes())
  .use(router.allowedMethods());
router.get|put|post|patch|delete|del
router
  .get('/', (ctx, next) => {
    ctx.body = 'Hello World!';
  })
  .post('/users', (ctx, next) => {
    // ...
  })
  .put('/users/:id', (ctx, next) => {
    // ...
  })
  .del('/users/:id', (ctx, next) => {
    // ...
  })
  .all('/users/:id', (ctx, next) => {
    // ...
  });
router.use —— 路由中间件

router.use(path,路由.routes(),路由.allowedMethods())

const Koa = require("koa")
const Router = require("koa-router")
const userRouter = require("./routers/user")

const app = new Koa()
const router = new Router()

// 注册路由
router.use("/user",userRouter.routes(),userRouter.allowedMethods())

// 应用
app.use(router.routes()).use(router.allowedMethods())

app.listen(8080)

router.prefix() —— 统一加前缀
const router = new Router()
// 统一加前缀
router.prefix("/api")
router.redirect —— 重定向路由

router.redirect(source, destination, [code])

  • source —— 源
  • destination —— 跳转目标
  • code —— 回调函数
router.redirect('/login', 'sign-in');

当访问 /login 页面时,会重定向到 sign-in 页面

koa-static 获取静态资源

文档地址:https://github.com/koajs/static#readme

安装:npm install koa-static

语法

import Koa from "koa"; // CJS: require('koa');
import serve from "koa-static"; // CJS: require('koa-static')
const app = new Koa();
app.use(serve(root, opts));

root: 根目录
opts : 你要访问的那个目录

const Koa = require("koa")
const path = require("path")
const app = new Koa()
// 静态资源
const server = require("koa-static")
app.use(server(path.join(__dirname,"public")))

app.listen(8080)

koa-static-cache 获取静态资源

文档地址:https://github.com/koajs/static-cache#readme

安装:npm install koa-static-cache

const static = require("koa-static-cache")

server.use(static({
  prefix: '/public',
  dir: "./public",
  dynamic: true,
  gzip: true
}))

获取请求参数

get参数

在koa中,获取GET请求源头时koa中request对象中的query方法或querystring方法,query返回是格式化号的参数对象,querystring返回的是请求字符串,由于ctx对request的API有直接引用方式,所以获取GET请求数据有两个途径。

  1. ctx.request.query,返回如 { a:1,b:2 }
  2. ctx.request.querystring ,返回如 a=1&b=2
post参数

对于post请求处理,koa-bodyparser 中间件可以把koa上下文的formData数据解析到ctx.request.body中

安装:npm install koa-bodyparser

文档地址:https://github.com/koajs/bodyparser

const Router = require("koa-router")
const KoaBody = require("koa-bodyparser")
const router = new Router()

router.get("/", async (ctx, next) => {
  ctx.set({
    "Content-Type": "text/html;charset=UTF-8"
  })
  ctx.response.body = "item/get"
})
  .post("/",KoaBody(), async (ctx, next) => {
    // 获取 post 请求的参数
    console.log(ctx.request.body)
  })
module.exports = router

ejs模板引擎

#安装 koa模板使用中间件
npm install --save koa-views
#安装ejs模板引擎
npm install --save ejs

cookie和session

cookie

koa提供了从上下文直接读取,写入cookie的方法

  • ctx.cookie.get(name,[options]) 读取上下文请求的cookie
  • ctx.cookie.set(name,value,[options]) 写入cookie
session

koa-session-minimal 提供存储介质的读写接口

在Nodejs中连接使用MySQL

  • http://www.npmjs.com/package/@mysql/xdevapi
  • http://www.npmjs.com/package/mysql2

Node MySQL 2

安装

npm install mysql2
回调版本:

const mysql = require(“mysql2”)

基于Promise 版本:

const mysql = require(“mysql2/promise”)

连接
// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});
创建连接池连接
const mysql = require("mysql2/promise")

// 创建连接池
const pool = mysql.createPool({
  host: "localhost", 
  user: "root", // 用户名
  password: "root", // 密码
  database: "user", //数据库名
  connectionLimit: 10,// 最大连接数
  waitForConnections: true, // 超过最大连接时排队
  queueLimit: 0, // 排队最大数量(0 代表不做限制)
})

常见MySQL应用场景案例

添加数据
// 连接数据库
const mysql = require("mysql2/promise")


async function pro_createConnection(username,password) {
  const pool = await mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root",
  database: "user"
})
 return pool
}


module.exports = pro_createConnection
const Router = require("koa-router")
const KoaBody = require("koa-bodyparser")
const router = new Router()
const itemMysql = require("../mysql/itemMysql")

router.get("/", async (ctx, next) => {

  const results = await itemMysql().then(res => res.query('SELECT * FROM `user_infos`'))
  ctx.body = results[0]
  
})

  .post("/", KoaBody(), async (ctx, next) => {
    const { username, password } = ctx.request.body
    await itemMysql().then(res => {
      res.query('INSERT INTO `user_infos` (`id`,`username`,`password`) VALUES (?,?,?)', [6, username, password])
    })

  })
module.exports = router

查询数据
where句子
组合条件
排序
限制查询位置与条数
更新数据
删除数据
函数
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Node.js 中使用 Koa 框架进行事务管理可以使用以下两种方式: 1. 使用数据库事务:如果你使用的是支持事务的数据库(如 MySQL、PostgreSQL 等),那么你可以使用数据库提供的事务功能来管理事务。在 Koa 中,你可以使用像 Sequelize 这样的 ORM 库来管理数据库操作。 例如,在 Sequelize 中使用事务的代码示例: ``` // 创建一个事务 const transaction = await sequelize.transaction(); try { // 在事务中执行数据库操作 await User.create({ name: 'John Doe' }, { transaction }); await Profile.create({ userId: 1, bio: 'Hello, world' }, { transaction }); // 提交事务 await transaction.commit(); } catch (error) { // 回滚事务 await transaction.rollback(); } ``` 在上面的示例中,我们使用了 `sequelize.transaction()` 方法来创建一个事务,并将其传递给每个数据库操作。如果其中任何一个操作失败,那么事务将会回滚,所有操作都将被撤销。 2. 使用 Koa 中间件:另一种管理事务的方法是使用 Koa 中间件来实现。你可以编写一个中间件函数,将所有需要在事务中执行的操作包裹起来,并在出现错误时回滚事务。 例如,在 Koa 中使用中间件管理事务的代码示例: ``` app.use(async (ctx, next) => { const transaction = await sequelize.transaction(); try { // 将事务对象绑定到上下文对象中 ctx.transaction = transaction; // 执行下一个中间件 await next(); // 提交事务 await transaction.commit(); } catch (error) { // 回滚事务 await transaction.rollback(); // 抛出错误 throw error; } }); // 在路由中使用事务 router.post('/users', async (ctx) => { // 从上下文对象中获取事务对象 const transaction = ctx.transaction; try { // 在事务中执行数据库操作 await User.create({ name: 'John Doe' }, { transaction }); await Profile.create({ userId: 1, bio: 'Hello, world' }, { transaction }); // 发送响应 ctx.body = { success: true }; } catch (error) { // 如果发生错误,将会自动回滚事务 throw error; } }); ``` 在上面的示例中,我们编写了一个 Koa 中间件函数,该函数会在每个请求中创建一个事务,并将其绑定到上下文对象中。在路由处理函数中,我们可以从上下文对象中获取事务对象,并使用它来执行数据库操作。如果任何一个操作失败,中间件将会回滚事务,并将错误抛出到全局错误处理函数中。 总的来说,使用数据库事务或 Koa 中间件来管理事务都是有效的方式。选择哪种方式取决于你的具体需求和项目的架构。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不是很菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值