How do I support multiple sites on the same server using hapi.js?

Let's say I want to host 2 of my sites on my server (cats.com and dogs.com) with one IP address (i.e. with virtual hosts). I want to write both of them using hapi.js and make them work as one process.

Sites can have overlapping paths, for example, they can have a /about page.

How could I implement this with hapi?

+5
source share
1 answer

A good way to achieve this with hapi is to put your different sites in the plugins section and use the vhost modifier when loading the plugin, ideally using Glue .

Here is an example:

sites /dogs.js

 exports.register = function (server, options, next) { // Put all your routes for the site in here server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Dogs homepage'); } }); next(); }; exports.register.attributes = { name: 'dogs' }; 

sites /cats.js

 exports.register = function (server, options, next) { // Put all your routes for the site in here server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Cats homepage'); } }); next(); }; exports.register.attributes = { name: 'cats' }; 

index.js

 const Glue = require('glue'); const Hoek = require('hoek'); const manifest = { connections: [{ port: 4000, }], registrations: [ { plugin: { register: './sites/cats' }, options: { routes: { vhost: 'cats.com' } } }, { plugin: { register: './sites/dogs' }, options: { routes: { vhost: 'dogs.com' } } } ] }; const options = { relativeTo: __dirname }; Glue.compose(manifest, options, (err, server) => { Hoek.assert(!err, err); server.start((err) => { Hoek.assert(!err, err); console.log('server started'); }); }); 

You can then confirm that routing is working correctly with a pair of cURL commands:

 $ curl -H "Host: cats.com" localhost:4000/ Cats homepage $ curl -H "Host: dogs.com" localhost:4000/ Dogs homepage 

The browser will set the Host header for you, although when you go to http://cats.com or http://dogs.com, hapi will provide you with the correct content (if your DNS is configured correctly).

+3
source

Source: https://habr.com/ru/post/1244105/


All Articles