简体   繁体   中英

Why does 'koa-static' middleware keeps returning 404?

I'm trying Koa by using koa-static. But it keeps returning 404 (Body: Not Found) when using multilevel inclusion relationship. I don't know the reason.

To reproduce ,

  • Windows 10 x64, Node v9.11.1
  • Koa v2.5.1, koa-compose v4.1.0, koa-static v4.0.3, koa-send v4.1.3

Directory:

index.html index.js sites/sites.js sites/onesite/index.js

index.html

Hello, koa

index.js

const Koa = require('koa')
const router = require('./sites/sites.js')
const app = new Koa()
app.use(router())
app.listen(80)

sites/sites.js

const compose = require('koa-compose')

module.exports = ()=>{
    return (ctx, next)=>{
        compose(require('./onesite').middleware)(ctx, next)
    }
}

sites/onesite/index.js

const Koa = require('koa')
const serve = require('koa-static')

const app = new Koa()
app.use(serve('.'))
module.exports = app

Your problem is in the router you return from sites.js :

module.exports = ()=>{
  return (ctx, next)=>{
    compose(require('./onesite').middleware)(ctx, next)
  }
}

compose is an async function, but you do not wait for its promise to finish. One way to solve this is to return the promise that is returned by compose so that koa knows that it has to wait for that promise to be resolved:

module.exports = ()=>{
  return (ctx, next)=>{
    return compose(require('./onesite').middleware)(ctx, next)
  }
}

Another way would be to use await :

module.exports = ()=>{
  return async (ctx, next)=>{
    await compose(require('./onesite').middleware)(ctx, next)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM