猿问

koa2中间件问题

const Koa = require('koa')

const static = require('koa-static')

const path = require('path')

const app = new Koa()


const test1 = async (ctx, next) => {

  console.log('test1')

  await next()

}


const test2 = (ctx, next) => {

  console.log('test2')

  next()

}


app.use(static(path.join(__dirname, 'dist')))

app.use(test1)

app.use(test2)



app.listen(8999, () => {

  console.log(8999)

})

进入localhost:8999后,test1,test2两个中间件没有被触发


跟koa-static调换位置之后


app.use(test1)

app.use(test2)

app.use(static(path.join(__dirname, 'dist')))

test1,test2两个中间件触发了,但koa-static没被触发。


难道koa-static没有next()么,并且为何调换位置后koa-static也触发不得


慕侠2389804
浏览 692回答 1
1回答

慕莱坞森

把第二个中间件写成异步的就可以了const test2 = async (ctx, next) => {  console.log('test2')  await next()}koa中间件执行后必须返回一个promise,如果非要用普通的函数写法,可以这样:const test2 =  (ctx, next) => {  return next().then(()=>{    console.log('test2')  })}如果你非要搞懂,可以看下这篇文章深入浅出koa2再补充一下,不知道你看完这个能不能理解const Koa = require('koa');const static = require('koa-static')const path = require('path')const app = new Koa();const test1 = async (ctx, next) => {  console.log('test1')  await next()}const test2 =  (ctx, next) => {  console.log('test2')  return next().then(()=>{    console.log('test3')  })}const test3 =  (ctx, next) => {  console.log('test4')  return next().then(()=>{    console.log('test5')  })}app.use(test1)app.use(test2)app.use(test3)app.use(static(path.join(__dirname, 'static')))app.listen(8080);// 打印结果test1test2test4test5test3
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答