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句子
组合条件
排序
限制查询位置与条数

更新数据

删除数据

函数

猜你喜欢

转载自blog.csdn.net/m0_62336865/article/details/129305077