Call a hapi route from another route

北城余情 提交于 2019-12-08 20:29:32

问题


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.

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.

Thanks.


回答1:


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).

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 and server.inject() are primarily used for testing but there are legitimate runtime uses like this too.

If you make a request to /route2, this will invoke /route1 handler and get the payload:

$ curl localhost:4000/route2
Hello World!


来源:https://stackoverflow.com/questions/33069573/call-a-hapi-route-from-another-route

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