如何使用node和hapi在同一端口上运行多个服务器标签?

时间:2015-07-22 16:46:27

标签: node.js hapijs

我正在尝试在同一节点代码堆栈上托管api和Web服务器。我使用标签,以便独立地将配置应用于每个服务器,但只有一个服务器工作。以下是代码:

var hapi = require('hapi');

// server definition
var server = new hapi.Server();
var runningPort = process.env.PORT || 3000;

// setting up connection
server.connection({
    host: '0.0.0.0',
    port: runningPort,
    labels: ['api']
});

server.connection({
    host: '0.0.0.0',
    port: runningPort,
    labels: ['web']
});



var webServer = server.select('web');
var apiServer = server.select('api');

// registering view engine
webServer.views({
    engines: { html: require('handlebars') },
    relativeTo: __dirname,
    path: './views',
    layoutPath: './views/layout',
    layout: 'default',
    partialsPath: './views/partials'
});

// registering hapi auth cookie and application authentication
webServer.register(
  {
    register: require('hapi-auth-cookie')
  }, 
  function (err) {
    if (err) {
      throw err;
    }

    var cache = webServer.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
    webServer.app.cache = cache;

    webServer.auth.strategy('session', 'cookie', true, {
        password: 'secret',
        cookie: 'sid-example',
        redirectTo: '/account/login',
        isSecure: false
    });
});

// registrations for api server
apiServer.register(
        {
            register: require('lout')
        },
    function (err) {
        if (err) {
            throw err;
        }
});

apiServer.register(require('hapi-auth-bearer-token'), function (err) {

    apiServer.auth.strategy('simple', 'bearer-access-token', {
        allowQueryToken: true,              // optional, true by default
        allowMultipleHeaders: false,        // optional, false by default
        accessTokenName: 'access_token',    // optional, 'access_token' by default
        validateFunc: function( token, callback ) {

            // For convenience, the request object can be accessed
            // from `this` within validateFunc.
            var request = this;

            // Use a real strategy here,
            // comparing with a token from your database for example
            if(token === "1234"){
                //## user object to be looked up here
                callback(null, true, { token: token })
            } else {
                callback(null, false, { token: token })
            }
        }
    });
});

//To do something to request before they passed on to routes
apiServer.ext('onRequest', function (request, reply) {
    //## we can get user object here off of the authToken
    utils.log('info', 'apiCall', {method: request.method, path: request.path})
    return reply.continue();
});

// register routes
webServer.route(webRoutes);
apiServer.route(apiRoutes);

server.start(function () {
    console.log('Web servers running at: ', 'localhost:' + runningPort);
    console.log('Api server running at: ', 'localhost:' + runningPort);
});

目前只有api路线有效。

2 个答案:

答案 0 :(得分:1)

如评论者所述,您无法在同一网络接口上创建与同一端口的2个连接。如果两个套接字试图在同一端口上侦听,这会一直回到listen syscall给出EADDRINUSE错误。

在不同的端口或单独的网络接口上创建两个连接完全可以:

server.connection({
    host: '127.0.0.1',
    port: 4000,
    labels: ['api']
});

server.connection({
    host: '127.0.0.1',
    port: 4001,
    labels: ['web']
});

答案 1 :(得分:1)

Matt已经说过,你不能在同一个端口上运行不同的连接。确保应用不同的端口,例如

server.connection({  
    host: 'localhost',
    port: process.env.PORT || port
});

server.connection({  
    host: 'localhost',
    port: process.env.PORT + 1 || port + 1
});

如果您想了解有关在同一个hapi项目中运行API和Web服务器的更多信息,可以浏览这些教程:

希望有所帮助!