【问题标题】:Can a Koa Application Use Another Koa Application?Koa 应用程序可以使用另一个 Koa 应用程序吗?
【发布时间】:2015-08-23 23:50:09
【问题描述】:

正如问题所暗示的,我无法将一个 koa 应用程序用作另一个应用程序的中间件。使用express,我们可以这样做:

const express = require('express');
const expressApp = express();
const otherExpressApp = express();

app.use(otherExpressApp);

同样的模式适用于connect。但是,它不适用于koa

const koa = require(`koa`);
const koaApp = koa();
const otherKoaApp = koa();

app.use(otherKoaApp);

给我:

AssertionError: app.use() requires a generator function
    at Application.app.use (/home/sean/repos/koaka/node_modules/koa/lib/application.js:100:5)
    at repl:1:5
    at REPLServer.defaultEval (repl.js:164:27)
    at bound (domain.js:250:14)
    at REPLServer.runBound [as eval] (domain.js:263:12)
    at REPLServer.<anonymous> (repl.js:392:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)
    at REPLServer.Interface._line (readline.js:546:8)

koa 提供了一个函数,可以将其作为express/connect 应用程序挂载:

expressApp.use(koaApp.callback());

但这似乎不适用于koa 本身:

koaApp.use(otherKoaApp.callback());

抛出:

AssertionError: app.use() requires a generator function
    at Application.app.use (/home/sean/repos/koaka/node_modules/koa/lib/application.js:100:5)
    at repl:1:7
    at REPLServer.defaultEval (repl.js:164:27)
    at bound (domain.js:250:14)
    at REPLServer.runBound [as eval] (domain.js:263:12)
    at REPLServer.<anonymous> (repl.js:392:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)
    at REPLServer.Interface._line (readline.js:546:8)

我可以将一个koa 应用程序用作另一个koa 应用程序的中间件吗? 如果可以,怎么做?如果不是,这种行为是否打算放在未来的版本中?为什么或为什么不?

【问题讨论】:

    标签: node.js middleware koa


    【解决方案1】:

    这样做的方法是使用koa-mount

    https://github.com/koajs/mount

    var koa = require('koa');
    var mount = require('koa-mount');
    var app1 = koa();
    var app2 = koa();
    app1.use(mount(app2));
    

    或者将其安装在 URL 子路径下:

    app1.use(mount('/api', app2));
    

    koa 与 express 的不同之处在于其内核非常小。例如,express 附带一个静态 Web 服务器中间件,但 koa 没有。您需要导入一个单独的模块来执行“X”这一事实只是在 koa 中完成的事情。但请注意,koa-mount 仍在旗舰 koajs github 仓库下,因此它或多或少是官方的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多