koa2《基础》

koa2的简介

介绍

- koa内部原理和结构都是基于http模块的,和express相像,语法和内部结构做了升级改造

- koa内部使用es6编写

主要特点

利用async函数来开发。

- koa1是用Generator生成器结合co模块来编写

- koa2用es2017的async和await来使用异步编程,更加简单

- koa本身没有引入任何路由

生态

- Egg.js

- 构建工具:vite

koa2的使用

使用前需要安装对应的包

基础应用

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

// Koa本身没有路由系统,只有中间件的功能
/**
 * ctx: context上下文对象
 * 请求
 * 响应
 */

// 使用任意的路径请求都可以
app.use(ctx=>{
  
    ctx.body = 'Hello Koa'
    console.log(ctx.req.method);// 获取请求方法
    console.log(ctx.req.url);//请求地址
    console.log(ctx.headers);// 请求头
    console.log(ctx.method);// 请求方法
})

app.listen(3000,()=>{
    console.log('http://localhost:3000')
})

koa中配置路由&静态资源托管&路由重定向

const Koa = require('koa')
const Router = require('@koa/router')
const static = require('koa-static')
const mount = require('koa-mount')
const path = require('path')


const router = new Router()

const app = new Koa()

/*1、在koa2中原生的路由方式*/   不推荐使用
// app.use(ctx=>{
//     console.log(ctx.path);//请求路径
//     const path = ctx.path
//     if(path === '/'){
//         ctx.body = 'home page'
//     }else if(path==='/welcome'){
//         ctx.body = 'welcome'
//     }else{
//         ctx.body = '404 not found'
//     }
// })

// 2、koa引入第三方路由,借助@koa/router,实现express中的路由

// router.get('/',(ctx) => {
//     ctx.body = 'home page'
// })
//
// router.post('/',ctx=>{
//     ctx.body = 'post /'
// })
//
// router.get('/users/:id',ctx=>{
//     ctx.body = `/users/${ctx.params.id}`
// })
//
// // 使用@koa/router要加上这一句来注册中间件
// app.use(router.routes()).use(router.allowedMethods())

// 3、静态资源托管
// npm install koa-static
// app.use(static("./public")) // 请求路径 http://localhost:3000/img/phone.jpg
// app.use(static(path.join(__dirname,"./public"))) // 请求路径 http://localhost:3000/phone.jpg

// 3.1、配置请求资源的前缀,处理跨域的前缀问题
// npm install koa-mount
// mount(前缀,资源地址)
app.use(mount('/foo',static(path.join(__dirname,"./public")))) //http://localhost:3000/foo/img/phone.jpg


// 4、路由重定向
router.get('/',ctx=>{
    // 请求http://localhost:3000/会自动把请求转发到http://localhost:3000/foo/img/phone.jpg,从而把资源给请求回来
    ctx.redirect('/foo/img/phone.jpg')
})
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000,()=>{
    console.log('http://localhost:3000')
})

koa的中间件

中间件的执行的栈结构(洋葱模型)&中间件的合成

异步中间件 => 异步函数

const Koa = require('koa')
const fs = require('fs')
const util = require('util')
const compose = require('koa-compose')


const app = new Koa()

// 注意:1、异步中间件要放到洋葱模型前面 

// 注册异步中间件
// 需求:读取文件中的内容,并且返回给前端页面
// app.use(async (ctx,next)=>{
//     // 读取文件
//     const readFile = util.promisify(fs.readFile)
//     const data = await readFile(('./views/index.html'))// 默认是返回文件,并且进行下载
//     ctx.type = 'html' // 告诉浏览器,要把返回的内容当作html解析,而不是当作文件下载
//     // 把data返回到前端页面
//     ctx.body = data
// })

// 洋葱模型
// const one = (ctx,next)=>{
//     console.log('>> one')
//     next()
//     console.log('<< one')
// }

// const two = (ctx,next)=>{
//     console.log('>> two')
//     next()
//     console.log('<< two')
// }

// const three = (ctx,next)=>{
//     console.log('>> three')
//     next()
//     console.log('<< three')
// }



// app.use(one)
// app.use(two)
// app.use(three)

// 中间件的合成 koa-compose
const one = (ctx,next)=>{
    console.log('>> one')
    next()
}

const two = (ctx,next)=>{
    console.log('>> two')
    next()
}

const three = (ctx,next)=>{
    console.log('>> three')
    next()
}

app.use(compose([one,two,three]))

app.listen(3000,()=>{
    console.log('http://localhost:3000')
})


koa中的错误处理


const Koa = require('koa')
const fs = require('fs')
const util = require('util')


const app = new Koa()

app.use(ctx=>{
    try{
        JSON.parse("{'name':'aaa'}") 
        ctx.body = 'hello Koa'
    }catch(err){
        ctx.response.status = 500
        ctx.response.body = '服务器内部错误=>' + err
    }finally{
        console.log('发生错误后仍然继续执行的代码')
    }
})


// 利用异常中间件来处理异常


app.listen(3000,()=>{
    console.log('http://localhost:3000')
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值