Hapi.js中的“挂载”(运行)遗留http处理程序

我做了一个Node.js聚会演示文稿,无法回答这个问题。 这仍然困扰着我。

假设我有一个传统的http应用程序或Express.js应用程序。 这是一种forms的function

function legacy_app(request, response) { // Handle the request. } 

假设我为我的应用程序的新版本采用Hapi.js。 但是我有很多debugging的遗留代码或上游代码,我希望将其集成到Hapi应用程序中。 例如,传统虚拟主机将运行旧版本,或者可以在URL中的/legacy命名空间内访问。

做这个的最好方式是什么?

包装现有的HTTP节点服务器调度函数作为一个hapi处理程序可能是好的,但你必须添加到你的hapi_wrap函数(在最后):

reply.close(false);

这样hapi就可以完成处理请求而不会干扰你的遗留逻辑( https://github.com/spumko/hapi/blob/master/docs/Reference.md#replycloseoptions )。

包装快速处理程序/中间件要复杂得多,因为您可能依赖于其他一些中间件(例如body parser,cookie parse,session等),并使用一些不属于节点的Express装饰器(例如res.send( ),res.json()等)。

我能想到的唯一办法就是手动。 只需直接打破文档中的build议即可:将原始请求和响应对象拉出并将其传递给旧式处理程序。

 // An application built with http core. var http = require('http') var legacy_server = http.createServer(legacy_handler) function legacy_handler(request, response) { response.end('I am a standard handler\n') } // An express application. var express = require('express') var express_app = express() express_app.get('*', function(request, response) { response.send('I am an Express app\n') }) // A Hapi application. var Hapi = require('hapi') var server = new Hapi.Server(8080, "0.0.0.0") server.route({path:'/', method:'*', handler:hapi_handler}) function hapi_handler(request, reply) { reply('I am a Hapi handler\n') } // Okay, great. Now suppose I want to hook the legacy application into the // newer Hapi application, for example under a vhost or a /deprecated namespace. server.route({path:'/legacy', method:'*', handler:hapi_wrap(legacy_handler)}) server.route({path:'/express', method:'*', handler:hapi_wrap(express_app)}) // Convert a legacy http handler into a Hapi handler. function hapi_wrap(handler) { return hapi_handler function hapi_handler(request, reply) { var req = request.raw.req var res = request.raw.res reply.close(false) handler(req, res) } } legacy_server.listen(8081) express_app.listen(8082) server.start() 

这似乎工作,虽然我会喜欢,如果谁知道哈比很好可以证实,这是没有缺陷。

 $ # Hit the Hapi application $ curl localhost:8080/ I am a Hapi handler $ # Hit the http application $ curl localhost:8081/ I am a standard handler $ # Hit the Express application $ curl localhost:8082/ I am an Express app $ # Hit the http application hosted by Hapi $ curl localhost:8080/legacy I am a standard handler $ # Hit the Express application hosted by Hapi $ curl localhost:8080/express I am an Express app