如何使Hapi插件仅适用于特定域或子域?

时间:2019-02-17 17:18:21

标签: javascript node.js subdomain url-routing hapijs

我的Hapijs项目中包含以下内容:

API插件 前端插件

然后,我有一个服务器文件夹,其中存放我的主index.js文件,在该文件中启动了Hapi服务器。我使用Glue插件将服务器文件夹中的所有内容链接在一起:https://www.npmjs.com/package/glue

我遇到的问题是我想为我的api使用一个子域,例如api.locahost:8000(api.domain.com)。但是,无论我键入哪种子域,我都可以访问我的网站。

此外,这就像random.localhost:8000转发到locahost: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 Glue.compose(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?他们需要成为两个单独的服务器吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

我认为这是不可能的,但是您可以使用生命周期方法来访问当前路径和域,然后可以在代码中插入某种逻辑来处理当前域。

例如,根据订单前后的需求更改生命周期。

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;
        })
    }
};