【问题标题】:Multiple connections on a hapi serverhapi 服务器上的多个连接
【发布时间】:2016-10-19 22:20:23
【问题描述】:

我想将插件添加到具有多个连接的 hapi 服务器,例如监听不同的 ip。

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

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

【问题讨论】:

    标签: hapijs


    【解决方案1】:

    默认情况下,插件会在调用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');
            })
        });
    });
    

    GET /plugin1 来自plugin1 的路由响应:

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

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

    http://localhost:8080/plugin2
    

    【讨论】:

    • @matt_harrison 将如何停止服务器上的单个端口(例如 8082)?
    • 仅供参考。 connection() 已在 v17 中删除
    【解决方案2】:

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

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

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2017-01-27
      • 2015-06-03
      • 1970-01-01
      • 2019-03-14
      相关资源
      最近更新 更多