首先在项目中安装koa
npm install koa --save
新建一个Js文件
const koa = require('koa')
const app = new koa()
// 使用
// app.use(async (ctx) => {
// ctx.body = 'hello koa'
// })
// 中间件机制
app.use(async (ctx, next) => {
ctx.body = '1'
next()
ctx.body += '2'
})
app.use(async (ctx, next) => {
ctx.body += '3'
next()
ctx.body += '4'
})
app.use(async (ctx, next) => {
ctx.body += '5'
next()
ctx.body += '6'
})
// 监听端口 3000 可以自定义
app.listen(3000)
ctx是上下文,next是执行下一个中间件
node运行js文件
浏览器访问 http://localhost:3000/
结果为 135642
koa有中间件机制 中间件机制是个洋葱环
第一个中间件执行完,next() 之后会执行第二个中间件,当执行到最后一个的时候,会一层层返回
执行到最后一个中间件,在从里往外一层层的返回执行
所以是135642的顺序