问题描述
我对HapiJS很新。我正在构建一个服务,我有两个路由/ route1和/ route2都使用插件架构。我已在我的清单文件中注册了两个插件。
I am pretty new to HapiJS. I am building a service where I have two routes /route1 and /route2 both are using the plugin architecture. I have registered both as plugins on my manifest file.
我想从/ route2调用/ route1,所以/ route2取决于来自/ route1的有效负载回复。我一直在寻找将/ route2的逻辑放在预处理程序的/ route1上,但我想将它们分开保存。
I want to call /route1 from /route2 so /route2 depends on the payload reply from /route1. I've been looking at putting the logic of /route2 on /route1 on the pre-handler but I want to keep them separately.
不知道如何从另一个调用已注册的插件,这两个插件(路由)正在发出网络请求。感谢您的阅读。
Don't know how to call a registered plugin from another the thing is that both plugins (routes) are making networks requests. Thanks for reading.
谢谢。
推荐答案
正如您指定的那样你不想使用共享的处理程序/路由先决条件(这将是我的第一选择),你可以使用http客户端发出实际请求(,,等。
As you specify that you don't want to use a shared handler/route prerequisite (which would be my first choice), you could make an actual request using a http client (Wreck, request, http or the like).
另一种不涉及实际发出网络请求的更有效的方法是使用hapi的内置方法/ A>。这将向您的服务器注入一个请求并获取您可以使用的响应。这是一个例子:
Another, more efficient way that doesn't involve actually making a network request is to use hapi's built-in server.inject()
method provided by Shot. This will inject a request into your server and get the response, which you can use. Here's an example:
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');
});
});
请注意,路径在插件中的事实无关紧要。我只是把它包括在内,所以它接近你的情况。
Note that the fact the routes are in plugins here is irrelevant. I've merely included it so it's close to your situation.
Shot和 server.inject()
主要是用于测试,但也有合法的运行时用途。
Shot and server.inject()
are primarily used for testing but there are legitimate runtime uses like this too.
如果您向 / route2
发出请求,这将调用 / route1
处理程序并获取有效负载:
If you make a request to /route2
, this will invoke /route1
handler and get the payload:
$ curl localhost:4000/route2
Hello World!
这篇关于从另一条路线呼叫hapi路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!