Koa.js笔记

一、路由

可以使用router的库
koa没有路由处理,需要自己去找库

二、静态资源处理

npm i koa-static
如果路径想使用别名,需要引入另一个包
npm i koa-mount

路由重定向

router.get('/bar', ctx => {
  ctx.redirect('/foo')
})

三、中间件执行栈结构

洋葱模型

先进后出
如果没有next()就不会往下走

const fs = require('fs')
const mount = require('koa-mount')
const util = require('util')

const app = new Koa()


app.use(async (ctx, next) => {
  const data = await util.promisify(fs.readFile)('./views/index.html','utf8')
  ctx.type = 'html'
  ctx.body = data
  next()
})

四、中间件合并处理

npm i koa-compose

const compose = require('koa-compose')

// a1、a2、a3是三个中间件
app.use(compose([a1,a2,a3]))

五、中间件异常处理

app.use(ctx => {
  try {
    JSON.parse('ABCDE')
    ctx.body = 'hello koa'
  } catch (err) {
    // ctx.response.status = 500
    // ctx.response.body = '服务端内部错误'
    ctx.throw(500)
  }
})

如果不想在每个中间件中写的话,可以在最外面写一个

// 在最外层添加异常捕获的中间件
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.status = 500
    ctx.body = '服务端内部错误'
  }
})

六、Koa的异常处理

app.on('error',err => {
  console.log("app error", err);
})

每个请求都会创建一个独立的Context上下文对象,它们之间不会互相污染

posted @ 2023-05-27 03:28  喵喵队立大功  阅读(28)  评论(0编辑  收藏  举报