如何使Hapi插件仅适用于特定域或子域?
我在Hapijs项目中有以下内容:
API插件前端插件
然后我有一个服务器文件夹,其中包含我的主index.js文件,其中启动了Hapi服务器。我使用Glue插件将所有内容链接在我的服务器文件夹中:
我遇到的问题是我想为我的api使用子域名,例如api.locahost:8000(api.domain)。但是,无论我输入什么类型的子域,我都可以访问我的网站。
此外,它就像random.localhost:8000转发到localhost:8000,我仍然可以访问我的所有网站的页面。
这是我的代码:
'use strict';
const Dotenv = require('dotenv');
Dotenv.config({ path: `${__dirname}/.env` });
const Glue = require('glue');
const manifest = {
server: {
port: process.env.PORT,
host: process.env.HOST
},
register: {
plugins: [
{
plugin: '~/api',
options: {
routes: {
vhost: process.env.SUBDOMAIN //api.localhost
}
}
},
{
plugin: '~/lib'
}
],
options: {
}
}
};
const options = {
relativeTo: __dirname
};
const startServer = async function () {
try {
const server = await Gluepose(manifest, options);
await server.start();
await console.log(`Server running at: ${server.info.uri}`);
}
catch (err) {
console.error(err);
process.exit(1);
}
};
startServer();
如果你想知道“lib”是什么,那就是我的前端目录名。如果您查看api插件选项,您可以看到我添加了子域的位置。
我怎么能这样做,所以我的前端插件只使用localhost:8000,我的API插件只使用api.localhost:8000?他们需要是两个独立的服务器吗?
提前致谢。
回答如下:我不相信这是可能的,但您可以使用生命周期方法来访问当前路径和域,然后您可以在代码中插入某种逻辑来处理当前域。
例如,在订单之前或之后根据您的需求更改生命周期。
exports.plugin = {
register: async function (server, options) {
server.ext('onPreHandler', async (request, h) => {
if(request.info.host !== 'YOUR_DOMAIN') return h.continue;
// you can check request.path also
// rest of the code...
return h.continue;
})
}
};
如何使Hapi插件仅适用于特定域或子域?
我在Hapijs项目中有以下内容:
API插件前端插件
然后我有一个服务器文件夹,其中包含我的主index.js文件,其中启动了Hapi服务器。我使用Glue插件将所有内容链接在我的服务器文件夹中:
我遇到的问题是我想为我的api使用子域名,例如api.locahost:8000(api.domain)。但是,无论我输入什么类型的子域,我都可以访问我的网站。
此外,它就像random.localhost:8000转发到localhost:8000,我仍然可以访问我的所有网站的页面。
这是我的代码:
'use strict';
const Dotenv = require('dotenv');
Dotenv.config({ path: `${__dirname}/.env` });
const Glue = require('glue');
const manifest = {
server: {
port: process.env.PORT,
host: process.env.HOST
},
register: {
plugins: [
{
plugin: '~/api',
options: {
routes: {
vhost: process.env.SUBDOMAIN //api.localhost
}
}
},
{
plugin: '~/lib'
}
],
options: {
}
}
};
const options = {
relativeTo: __dirname
};
const startServer = async function () {
try {
const server = await Gluepose(manifest, options);
await server.start();
await console.log(`Server running at: ${server.info.uri}`);
}
catch (err) {
console.error(err);
process.exit(1);
}
};
startServer();
如果你想知道“lib”是什么,那就是我的前端目录名。如果您查看api插件选项,您可以看到我添加了子域的位置。
我怎么能这样做,所以我的前端插件只使用localhost:8000,我的API插件只使用api.localhost:8000?他们需要是两个独立的服务器吗?
提前致谢。
回答如下:我不相信这是可能的,但您可以使用生命周期方法来访问当前路径和域,然后您可以在代码中插入某种逻辑来处理当前域。
例如,在订单之前或之后根据您的需求更改生命周期。
exports.plugin = {
register: async function (server, options) {
server.ext('onPreHandler', async (request, h) => {
if(request.info.host !== 'YOUR_DOMAIN') return h.continue;
// you can check request.path also
// rest of the code...
return h.continue;
})
}
};