【问题标题】:Why does 'koa-static' middleware keeps returning 404?为什么“koa-static”中间件不断返回 404?
【发布时间】:2018-05-27 08:57:36
【问题描述】:

我正在使用 koa-static 来尝试 Koa。但是在使用多级包含关系时,它会不断返回404 (Body: Not Found)。不知道是什么原因。

重现

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

目录:

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

【问题讨论】:

    标签: javascript node.js koa koa2 koa-router


    【解决方案1】:

    你的问题出在你从sites.js返回的路由器上:

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

    compose 是一个异步函数,但您不必等待它的承诺完成。解决此问题的一种方法是返回由 compose 返回的承诺,以便 koa 知道它必须等待该承诺得到解决:

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

    另一种方法是使用await:

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

    【讨论】:

    • 非常感谢!调试了好久。
    猜你喜欢
    • 2021-08-09
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2015-08-14
    • 1970-01-01
    • 2010-11-12
    相关资源
    最近更新 更多