如何将Hapi.js插件应用于特定路由?

nop*_*ato 2 javascript node.js hapijs

我有一个用Hapi.js构建的服务器.我创建了一个插件来限制对某些本地网络IP地址的访问,如下所示:

exports.register = function (server, options, next) {
    server.ext({
        type: 'onRequest',
        method: function (request, reply) {
            console.log(request);
            if (
                request.info.remoteAddress.indexOf("192.") !== 0 &&
                request.info.remoteAddress.indexOf("127.") !== 0
            ) {
                return reply.view('error', {
                    error: "I DON'T LIKE YOU"
                });
            }
            return reply.continue();
        }
    });
    next();
};

exports.register.attributes = {
    pkg: { "name": "localOnly" }
};
Run Code Online (Sandbox Code Playgroud)

我想将此插件仅应用于"/ pathA",同时保持所有用户都可以访问"/ pathB"和"/ pathC".因此我尝试这样做:

const server = new Hapi.Server();
server.connection({ port: 8000 });
server.register(require('vision'), err => {
    if (err) throw err;
    server.views(/* removed for brevity */);
    server.route({ method: 'GET', path: '/pathB', handler: handlerB });
    server.route({ method: 'GET', path: '/pathC', handler: handlerC });
    server.register(require('./plugins/localOnly.js'), err => {
        if (err) throw err;
        server.route({ method: 'GET', path: '/pathA', handler: handlerA });
        server.start(/* removed for brevity */);
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,似乎我的插件拦截了所有连接.谁能告诉我我做错了什么?如果你建议我做一个完整的重构,那没关系.我只是在这个阶段计划应用程序,并希望给Hapi.js一个机会.

Mat*_*son 6

它需要在插件中吗?如果没有,您可以使用路由级别扩展点.例如:

路线级扩展

const restrict = function (request, reply) {

    if (/^(192|127)/.test(request.info.remoteAddress)) {
        return reply('Blocked');
    }

    return reply.continue();
};

server.route({
    config: {
        ext: {
            onPreAuth: { method: restrict }
        }
    },
    method: 'GET',
    path: '/pathA',
    handler: function (request, reply) {

        reply('Hello!');
    }
});
Run Code Online (Sandbox Code Playgroud)

另一种使用插件的方法:

使用在插件中添加路由 sandbox: plugin

const plugin = function (server, options, next) {

    const restrict = function (request, reply) {

        if (/^(192|127)/.test(request.info.remoteAddress)) {
            return reply('Blocked');
        }

        return reply.continue();
    };

    // only applies to route in this plugin

    server.ext('onPreAuth', restrict, { sandbox: 'plugin' }); 

    server.route({
        method: 'GET',
        path: '/pathA',
        handler: function (request, reply) {

            reply('Hello!');
        }
    });

    return next();
};
Run Code Online (Sandbox Code Playgroud)


Bre*_*dan 5

对于较新版本的 Hapi(当前为 v17),您将需要传递路由选项,route.options.plugins['myPluginName']例如

{
  method: 'GET',
  path: '/home',
  options: {
    plugins: {
       myPluginName: true
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ext这可以在挂钩或稍后的插件中找到onPreAuth。例如

register: async (server, options) => {
  server.ext({
    type: 'onPreAuth',
    method: async (request, h) => {
      // Exit early if the route is not configured for this route
      if (!request.route.settings.plugins.myPluginName) { return h.continue }
      // ... runs before the route handler ...
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

请注意,挂钩必须晚于Hapi 生命周期onRequest,因为此时尚未加载路由。如果您想访问身份验证内容,那么您将必须使用.onPostAuth

这种方法的优点是路由和插件之间松散耦合。