hapi服务器上的多个连接

时间:2015-08-07 20:26:53

标签: hapijs

我想将插件添加到hapi服务器,该服务器具有多个连接,例如在不同的ips上侦听。

是否可以为所有配置的服务器添加插件?

或者如何遍历所有服务器以将插件添加到所有服务器?

2 个答案:

答案 0 :(得分:4)

默认情况下,插件会在调用server.route()时为所有连接添加路由。

要限制插件添加路由的连接,可以在创建连接时使用标签,然后在注册插件时指定这些标签。这是一个例子:

var Hapi = require('hapi');

var server = new Hapi.Server();

server.connection({ port: 8080, labels: 'a' });
server.connection({ port: 8081, labels: 'b' });
server.connection({ port: 8082, labels: 'c' });

var plugin1 = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/plugin1',
        handler: function (request, reply) {

            reply('Hi from plugin 1');
        }
    });

    next();
};
plugin1.attributes = { name: 'plugin1' };

var plugin2 = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/plugin2',
        handler: function (request, reply) {

            reply('Hi from plugin 2');
        }
    });

    next();
};
plugin2.attributes = { name: 'plugin2' };

server.register(plugin1, function (err) {

    if (err) {
        throw err;
    }

    server.register(plugin2, { select : ['a'] }, function (err) {

        if (err) {
            throw err;
        }

        server.start(function () {

            console.log('Server started');
        })
    });
});
来自plugin1

GET / plugin1 路由响应:

http://localhost:8080/plugin1
http://localhost:8081/plugin1
http://localhost:8081/plugin2

来自plugin2 GET / plugin2 路由仅响应:

http://localhost:8080/plugin2

答案 1 :(得分:1)

您可以在hapi中创建多个connections以使多个内部服务器可用。这些分离服务器的优点是:您可以仅为需要该功能的服务器单独注册插件和路由。

how to separate frontend and backend within a single hapi project上的本教程中查找更多详细信息。

希望有所帮助!

相关问题