假设我想将我的2个网站(cats.com和dogs.com)托管在具有单个IP地址(即虚拟主机)的同一服务器上。我想同时使用hapi.js编写它们,并使它们作为单个进程运行。
这些站点可能具有重叠的路径,例如,它们可能都具有/about
页面。
我如何用hapi来实现呢?
使用hapi实现此目的的一种好方法是将您的不同站点放在单独的插件中,并vhost
在加载插件时使用修饰符,最好使用Glue。
这是一个例子:
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');
});
});
然后,您可以使用几个cURL命令来确认路由正常工作:
$ curl -H "Host: cats.com" localhost:4000/
Cats homepage
$ curl -H "Host: dogs.com" localhost:4000/
Dogs homepage
不过,浏览器会为您设置该主机标头,因此当您浏览至http://cats.com或http://dogs.com时, hapi将为您提供正确的内容(前提是您的DNS配置正确)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句