How to store routes in separate files when using Hapi?

前端 未结 7 1947
醉话见心
醉话见心 2021-01-30 01:49

All of the Hapi examples (and similar in Express) shows routes are defined in the starting file:

var Hapi = require(\'hapi\');

var server = new Hapi.Server();
s         


        
相关标签:
7条回答
  • 2021-01-30 02:21

    I know this is already approved. I put down my solution in case someone wants a quick fix and new to Hapi.

    Also I included some NPM too so Newbees can see how to to use the server.register with multiple plugin in the case ( good + hapi-auto-route )

    Installed some npm packages:

    npm i -S hapi-auto-route
    
    npm i -S good-console
    
    npm i -S good
    
    
    // server.js
    'use strict';
    
    const Hapi = require('hapi');
    const Good = require('good');
    const AutoRoute = require('hapi-auto-route');
    
    const server = new Hapi.Server();
    
    server.connection(
        {   
            routes: { cors: true }, 
            port: 3000, 
            host: 'localhost',
            labels: ['web']
        }
    );
    
    server.register([{
        register: Good,
        options: {
            reporters: {
                console: [{
                    module: 'good-squeeze',
                    name: 'Squeeze',
                    args: [{
                        response: '*',
                        log: '*'
                    }]
                }, {
                    module: 'good-console'
                }, 'stdout']
            }
        }
    }, {
        register: AutoRoute,
        options: {}
    }], (err) => {
    
         if (err) {
            throw err; // something bad happened loading the plugin
        }
    
        server.start((err) => {
    
            if (err) {
                throw err;
            }
            server.log('info', 'Server running at: ' + server.info.uri);
        });
    });
    

    In your routes/user.js

    module.exports = 
    [   
         {  
            method: 'GET',
            path: '/',
            handler: (request, reply) => {
                reply('Hello, world!');
            } 
        },  
         {  
            method: 'GET',
            path: '/another',
            handler: (request, reply) => {
                reply('Hello, world again!');
            } 
        },
    ];
    

    Now run: node server.js

    Cheers

    0 讨论(0)
提交回复
热议问题