Mount Koajs app on top of Express

血红的双手。 提交于 2019-12-22 11:10:27

问题


From koajs.com:

app.callback()

Return a callback function suitable for the http.createServer() method to handle a request. You may also use this callback function to mount your koa app in a Connect/Express app.

Now I have an Express app that already starts its own http server. How can I mount a koa app on top of this existing server, so that it shares the same port?

Would I include the koa app as an Express middlware? Do I still use app.callback() for that?


回答1:


expressapp.use(koaapp.callback()) is fine. but remember, koaapp.callback() does not have a next, so there's no passing errors to the express app or skipping the koaapp once you use it.

it's better to keep them completely separate since their APIs are incompatible

var koaapp = koa()
var expressapp = express()
http.createServer(req, res) {
  if (true) koaapp(req, res);
  else expressapp(req, res);
})



回答2:


Since you need a server instance in order to mount a middleware on a specific /prefix, it would be something like

var http = require('http');
var expressApp = require('express');
var koaApp = require('koa');

// ...

expressApp.use('/prefix', http.createServer(koaApp.callback()));


来源:https://stackoverflow.com/questions/21889898/mount-koajs-app-on-top-of-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!