课程名称:SpringBoot2.X + Vue + UniAPP,全栈开发医疗小程序
课程章节: 第一章
课程讲师:神思者
安装koa
npm i koa
const Koa = require('koa') const app = new Koa() app.use((ctx, next) => { console.log('one-1'); next() console.log('one-2'); }) app.use((ctx, next) => { console.log('two-1'); next() console.log('two-2'); }) app.use((ctx, next) => { console.log('three-1'); next() console.log('three-2'); }) app.listen(3000,()=>{ console.log('http://127.0.0.1:3000') })
app.listen 设置端口号
koa 使用得是 洋葱圈模式
也就是 后进先出
所以上面得代码 得输出
当使用异步得方式时
const Koa = require('koa') const app = new Koa() app.use(async(ctx, next) => { console.log('one-1'); next() console.log('one-2'); }) app.use(async(ctx, next) => { await console.log('two-1'); next() await console.log('two-2'); }) app.use(async(ctx, next) => { console.log('three-1'); next() console.log('three-2'); }) app.listen(3000,()=>{ console.log('http://127.0.0.1:3000') })
koa得router插件
npm i @koa/router
router文件夹下 - index.js文件
const Router = require('@koa/router') const router = new Router({prefix: '/api/v1'}) router.get('/user', ctx=>{ ctx.body = 'userssss' }) router.get('/video', ctx=>{ ctx.body = 'video' }) module.exports = router
app.js
const Koa = require('koa') const router = require('./router/index') const app = new Koa() app.use(router.routes()) app.listen(3000,()=>{ console.log('http://127.0.0.1:3000') })
获得传值信息
router.get('/video/:id', ctx=>{
ctx.body = 'video'
console.log(ctx.query)
console.log(ctx.params)
})