javascriptnode.jskoakoa2koa-router

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,

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

Solution

  • 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)
      }
    }