当您指定不想使用共享处理程序/路由先决条件(这将是我的第一选择)时,您可以使用 http 客户端发出实际请求(Wreck https://github.com/hapijs/wreck, request https://github.com/request/request, http https://nodejs.org/api/http.html或类似)。
另一种不涉及实际发出网络请求的更有效方法是使用 hapi 的内置方法server.inject() https://github.com/hapijs/shot方法提供者Shot https://github.com/hapijs/shot。这会将请求注入您的服务器并获取您可以使用的响应。这是一个例子:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 4000 });
var plugin1 = function (server, options, next) {
server.route({
method: 'GET',
path: '/route1',
handler: function (request, reply) {
reply('Hello');
}
});
next();
};
plugin1.attributes = { name: 'plugin1' };
var plugin2 = function (server, options, next) {
server.route({
method: 'GET',
path: '/route2',
handler: function (request, reply) {
server.inject('/route1', function (res) {
reply(res.payload + ' World!');
});
}
});
next();
};
plugin2.attributes = { name: 'plugin2' };
server.register([plugin1, plugin2], function (err) {
if (err) throw err;
server.start(function (err) {
if (err) throw err;
console.log('Started');
});
});
请注意,路由在插件中的事实与此处无关。我只是将其包括在内,以便它接近您的情况。
射击和server.inject()
主要用于测试,但也有像这样的合法运行时用途。
如果您提出请求/route2
,这将调用/route1
处理程序并获取有效负载:
$ curl localhost:4000/route2
Hello World!